package com.cn.bulu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.cn.bulu.constant.PayMethod;
import com.cn.bulu.constant.TypeOfIndent;
import com.cn.bulu.constant.WorkerType;
import com.cn.bulu.dao.*;
import com.cn.bulu.pojo.*;
import com.cn.bulu.server.zhifubao.util.UtilDate;
import com.cn.bulu.server.zhifubao.util.httpClient.AlipayNotify;
import com.cn.bulu.service.MerchantsService;
import com.cn.bulu.service.MerchantsWalletRecordService;
import com.cn.bulu.service.WorkerWalletRecordService;
import com.cn.bulu.utils.*;
import com.cn.bulu.utils.ClothCurtain.Arith;
import com.cn.bulu.utils.MD5Utils.MD5Utils;
import com.cn.bulu.utils.Monery.zhifubao.OrderUtil;
import com.cn.bulu.utils.alipay.config.AlipayConfig;
import com.cn.bulu.utils.alipay.util.AlipayParams;
import com.cn.bulu.utils.jiguang.Jiguang;
import com.cn.bulu.utils.redis.JedisUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("merchantsService")
public class MerchantsServiceImpl implements MerchantsService {

	private static Logger logger = Logger.getLogger(MerchantsServiceImpl.class);

	@Resource
	private MerchantsDao merchantsDao;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private FactoryDao factoryDao;
	@Resource
	private RechargeDao rechargeDao;
	@Resource
	private MoneyRecordDao moneyRecordDao;
	@Resource
	private WorkerWalletRecordService workerWalletRecordService;
	@Resource
	private MerchantsWalletRecordService merchantswalletRecordService;

	// 下测量订单
	public BuluResult toAddMeasureIndent(HttpServletRequest request, String name, String phone, Long subscribeTime,
			Integer roomNumB, String province, String city, String area, String address, String remark) {
		String sign = request.getParameter("sign");
		////logger.error("sign==" + sign);
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));

		Customer_address customer_address = new Customer_address();
		customer_address.setProvince(province);
		customer_address.setCity(city);
		customer_address.setArea(area);

		// 查询该区对应的code
		String areaCode = getCodeByCityAndArea(city, area);
		////logger.error("areaCode==" + areaCode);
		customer_address.setAreaCode(areaCode);
		String provinceCode = workerDao.selectProvinceCodeForWorker(province);
		String cityCode = workerDao.selectCityCodeForWorker(city);
		String workerSpaceCodeStr = provinceCode + "/" + cityCode;
		customer_address.setCuAddressCodeStr(workerSpaceCodeStr);
		
		customer_address.setAddress(address);
		customer_address.setName(name);
		customer_address.setPhone(phone);
		merchantsDao.addNewCustomer_address(customer_address);
		// SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd
		// hh:mm:ss");
		Indent indent = new Indent();
		indent.setType(0);
		indent.setRoomNumB(roomNumB);
		indent.setCustomerId(merchantsId);
		indent.setBeginTime(new Date());
		Date aa = new Date(subscribeTime);
		indent.setSubscribeTime(aa);
		// try {
		// //logger.error(subscribeTime);
		// //logger.error(simpleDateFormat.parse(subscribeTime));
		// indent.setSubscribeTime(simpleDateFormat.parse(subscribeTime));
		// } catch (ParseException e) {
		// e.printStackTrace();
		// }
		indent.setIndentType(3);
		indent.setCuAdId(customer_address.getCuAdId());
		// 根据市查询测量费后根据房间数计算测量费
		// //logger.error(shi);
		Map<String, Object> map = merchantsDao.selectCPriceByCity(city, 1);
		Map<String, Object> mapGR = merchantsDao.selectCPriceByCity(city, 0);
		Double indentPrice = 0.0;
		Double merchantsPrice = 0.0;
		// //logger.error(roomNumB);selectXiangqing
		// //logger.error(map.get("roomNumber"));

		merchantsPrice = meaPrice(map, roomNumB, merchantsPrice);
		indentPrice = meaPrice(mapGR, roomNumB, indentPrice);
        indent.setWorkerRealPrice(indentPrice);
		indent.setMerchantsRealPrice(merchantsPrice);
		// 查询安心宝价格
		Double relievedPrice = (Double) map.get("relievedPrice");
		// merchantsPrice = Arith.add(merchantsPrice, relievedPrice);
		//
		indent.setIndentPrice(indentPrice);
		////logger.error(indent.getIndentPrice());
		indent.setMerchantsPrice(merchantsPrice);
		indent.setRelievedPrice((Double) map.get("relievedPrice"));
		indent.setRemark(remark);
		//indent.setOrderId(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId));
		indent.setIsNeedTakeGoods(0);//测量单都设置为不需要取货
		merchantsDao.addNewIndentOfMeasure(indent);
		// 根据订单号查询一些信息
		Map<String, Object> send = merchantsDao.selectIndent(indent.getIndentId());

		send.put("relievedPrice", relievedPrice);
		Map<String, Object> peifu = merchantsDao.selectPeifu(1);
		// 查询每次加价价格
		Double premium = merchantsDao.selectPremium();
		send.put("premium", premium);
		// 根据市获取电机每台单价
		Double dianjiPrice = (Double) map.get("motorPrice");
		send.put("dianji", (String) peifu.get("beginString") + dianjiPrice + (String) peifu.get("overString"));
		Map<String, Object> beizhu = merchantsDao.selectPeifu(2);
		send.put("jiajiabeizhu", beizhu.get("beginString"));
		Map<String, Object> anxinbao = merchantsDao.selectPeifu(3);
		send.put("anxinbao",
				(String) anxinbao.get("beginString") + relievedPrice + (String) anxinbao.get("overString"));
		send.put("merchantsPrice", Arith.add(merchantsPrice, relievedPrice));
		send.put("dianjiPrice", dianjiPrice);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 获取一定窗帘数量的测量价格
	private double meaPrice(Map<String, Object> map, int roomNumB, double price) {
		double meaStartingFare = (double) map.get("meaStartingFare");// 测量起步价
		int meaBeyondNumOne = (Integer) map.get("meaBeyondNumOne");// 第一个阈值
		int meaBeyondNumTwo = (Integer) map.get("meaBeyondNumTwo"); // 第二个阈值
		double meaBeyUnitPriceOne = (double) map.get("meaBeyUnitPriceOne");// 过了第一个阈值后每个数据单价
		double meaBeyUnitPriceTwo = (double) map.get("meaBeyUnitPriceTwo");// 过了第二个阈值每个数据单价
		if (meaBeyondNumOne >= roomNumB) {// 测量房间数不超过第一个阀值(10)
			price = Arith.add(meaStartingFare, price);
		} else if (meaBeyondNumOne < roomNumB && meaBeyondNumTwo >= roomNumB) {// 大于第一个，小于等于第二个
			price = Arith.add((roomNumB - meaBeyondNumOne) * meaBeyUnitPriceOne, meaStartingFare);
		} else {
			price = Arith.add(Arith.add(10 * meaBeyUnitPriceOne, meaStartingFare),
					(roomNumB - meaBeyondNumTwo) * meaBeyUnitPriceTwo);
		}
		return price;
	}

	// 下维修单
	public BuluResult toAddRepairIndent(HttpServletRequest request, String name, String phone, Long subscribeTime,
			String weiXbody, String province, String city, String area, String address, Double merchantsPrice,
			String baseAddress, String detailAddress, String remark, String takeGoodsTel, Integer isNeedTakeGoods) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));

		// 地址信息放到Customer_address中，便于存到表中
		Customer_address customer_address = new Customer_address();
		customer_address.setProvince(province);
		customer_address.setCity(city);
		customer_address.setArea(area);

		// 查询该区对应的code
		String areaCode = getCodeByCityAndArea(city, area);
		//logger.error("areaCode==" + areaCode);
		customer_address.setAreaCode(areaCode);
		String provinceCode = workerDao.selectProvinceCodeForWorker(province);
		String cityCode = workerDao.selectCityCodeForWorker(city);
		String workerSpaceCodeStr = provinceCode + "/" + cityCode;
		customer_address.setCuAddressCodeStr(workerSpaceCodeStr);

		customer_address.setAddress(address);
		customer_address.setName(name);
		customer_address.setPhone(phone);
		merchantsDao.addNewCustomer_address(customer_address);
		// 再把id存到indent中 type=2 weiXbody indentType=2 beginTime subscribeTime
		Map<String, Object> priceMap = merchantsDao.selectCPriceByCity(city , 1);
		Indent indent = new Indent();
		indent.setWorkerRealPrice(merchantsPrice);
		indent.setMerchantsRealPrice(merchantsPrice);
		indent.setType(2);
		indent.setWeiXbody(weiXbody);
		indent.setBeginTime(new Date());
		indent.setCustomerId(merchantsId);
		// //logger.error(quHAddress);
		// indent.setRelievedBao(relievedBao);
		// 根据市查询出每单提取多少钱
		Double danti = merchantsDao.selectDanti(city);
		Map<String, Object> map = merchantsDao.selectCPriceByCity(city, 1);
		Double relievedPrice = (Double) map.get("relievedPrice");// 安心宝价格
		Double repairStartingFare = (Double) map.get("repairStartingFare");// 维修起步价
		Double indentPrice = Arith.sub(Math.max(merchantsPrice, repairStartingFare), danti);
		// merchantsPrice = Arith.add(Math.max(merchantsPrice,
		// repairStartingFare), relievedPrice);
		merchantsPrice = Math.max(merchantsPrice, repairStartingFare);
		// if (isNeedTakeGoods == 1) {// 取货电话为下单人电话时，认为不需要去其他地方取货，不加取货费用
		// Double takeGoodsPrice = (Double) map.get("takeGoodsPrice");// 取货价格
		// merchantsPrice = Arith.add(merchantsPrice, takeGoodsPrice);
		// indentPrice = Arith.add(indentPrice, takeGoodsPrice);
		// }
		indent.setIsNeedTakeGoods(isNeedTakeGoods);
		if (isNeedTakeGoods == 1) {
			Double takeGoodsCost = merchantsDao.selectTakeGoodsCost(city);
			indentPrice = Arith.add(indentPrice, takeGoodsCost);
			merchantsPrice = Arith.add(merchantsPrice, takeGoodsCost);
			indent.setTakeGoodsTel(takeGoodsTel);
			indent.setBaseAddress(baseAddress);
			indent.setDetailAddress(detailAddress);
			
		} else {
			indent.setTakeGoodsTel("无");
			indent.setBaseAddress("无");
			indent.setDetailAddress("无");
		}
		indent.setIndentPrice(indentPrice);
		indent.setMerchantsPrice(merchantsPrice);
		indent.setSubscribeTime(new Date(subscribeTime));
		// try {
		// indent.setSubscribeTime(simpleDateFormat.parse(subscribeTime));
		// } catch (ParseException e) {
		//
		// e.printStackTrace();
		// }
		indent.setIndentType(3);
		indent.setCuAdId(customer_address.getCuAdId());
		indent.setRemark(remark);
		//indent.setOrderId(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId));
		merchantsDao.addNewIndentOfRepair(indent);
		// 根据订单号查询一些信息
		Map<String, Object> send = merchantsDao.selectIndent(indent.getIndentId());
		if (send.get("baseAddress") == null) {
			send.put("baseAddress", "");
			send.put("detailAddress", "");
		}
		send.put("relievedPrice", relievedPrice);
		Map<String, Object> peifu = merchantsDao.selectPeifu(1);
		// 根据市获取电机每台单价
		Double dianjiPrice = merchantsDao.selectDianjiPrice(city);
		// 电机备注
		send.put("dianji", (String) peifu.get("beginString") + dianjiPrice + (String) peifu.get("overString"));
		Map<String, Object> beizhu = merchantsDao.selectPeifu(2);
		// 加价备注
		send.put("jiajiabeizhu", beizhu.get("beginString"));
		Map<String, Object> anxinbao = merchantsDao.selectPeifu(3);
		// 安心宝备注
		send.put("anxinbao",
				(String) anxinbao.get("beginString") + relievedPrice + (String) anxinbao.get("overString"));
		send.put("merchantsPrice", merchantsPrice);
		send.put("dianjiPrice", dianjiPrice);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 下安装订单
	public BuluResult toAddAnzhuangIndent(HttpServletRequest request, String duogechuanglian, String name, String phone,
			Long subscribeTime, String province, String city, String area, String address, String baseAddress,
			String detailAddress, String remark, String takeGoodsTel, Integer isNeedTakeGoods) {
		//获取添加商品人
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 把安装地址存到地址中并获取id
		Customer_address customer_address = new Customer_address();
		customer_address.setProvince(province);
		customer_address.setCity(city);
		customer_address.setArea(area);
		// 查询安装地址地区对应的code
		String areaCode = getCodeByCityAndArea(city, area);
		customer_address.setAreaCode(areaCode);
		String provinceCode = workerDao.selectProvinceCodeForWorker(province);
		String cityCode = workerDao.selectCityCodeForWorker(city);
		String workerSpaceCodeStr = provinceCode + "/" + cityCode;
		customer_address.setCuAddressCodeStr(workerSpaceCodeStr);
		
		customer_address.setAddress(address);
		customer_address.setName(name);
		customer_address.setPhone(phone);
		merchantsDao.addNewCustomer_address(customer_address);
		// 创建id原型，给订单的各个字段赋值
		Indent indent = new Indent();
		indent.setType(1);
		indent.setBeginTime(new Date());
		indent.setSubscribeTime(new Date(subscribeTime));
		indent.setIndentType(3);
		// 把安装地址加到订单中
		indent.setCuAdId(customer_address.getCuAdId());
		indent.setRemark(remark);
		//判断该订单是否需要取货
		if (null == isNeedTakeGoods) {
			indent.setTakeGoodsTel("无");
		} else if (isNeedTakeGoods == 1) {
			indent.setTakeGoodsTel(takeGoodsTel);
			indent.setBaseAddress(baseAddress);
			indent.setDetailAddress(detailAddress);
		}else {
			indent.setTakeGoodsTel("无");
			indent.setBaseAddress("无");
			indent.setDetailAddress("无");
		}
		//保存是否取货的标志位
		indent.setIsNeedTakeGoods(isNeedTakeGoods == null ? 0 : isNeedTakeGoods);
		indent.setCustomerId(merchantsId);
		//我们自己产生的订单流水号
		//indent.setOrderId(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId));
		merchantsDao.insertAnzhuangIndent(indent);

		// 计算价格
		Double merchantsPrice = 0.0;// 商家应付款
		Double indentPrice = 0.0;
		//如果下订单时有商品，在这里保存商品
		//布艺帘
		if (duogechuanglian != null) {
			JSONArray jsonArray = JSONObject.parseArray(duogechuanglian);
			//logger.error("duogechuanglian++jsonArray===" + jsonArray.toJSONString());
			for (int a = 0; a < jsonArray.size(); a++) {
				JSONObject jsonObject = (JSONObject) jsonArray.get(a);
				//布艺帘中的Goods属性存放起来
				Goods goods = new Goods();
				if (jsonObject.get("locationId") != null) {// 房间类型id
					goods.setLocationId(jsonObject.getInteger("locationId"));
				} else {// 证明otherRoom不为空
					goods.setOtherRoom(jsonObject.getString("otherRoom"));
				}
				if (jsonObject.get("structure") != null) {// '0只要布 1只要纱 2布+纱'
					goods.setStructure(jsonObject.getInteger("structure"));
				}
				if (jsonObject.get("style") != null) {
					goods.setStyle(jsonObject.getInteger("style"));
				}
				if (jsonObject.get("installCase") != null) {
					goods.setInstallCase(jsonObject.getInteger("installCase"));
				}
				if (jsonObject.get("merchantsImg") != null) {
					goods.setMerchantsImg(jsonObject.getString("merchantsImg"));
				}
				if (jsonObject.get("shadingCloth") != null) {
					goods.setShadingCloth(jsonObject.getInteger("shadingCloth"));
				}
				goods.setType(jsonObject.getInteger("type"));
				// 把goods存到商品表中并获取id
				merchantsDao.insertGoods(goods);
				// 布配件
				if (jsonObject.get("bumishu") != null) {
					JSONArray buArray = jsonObject.getJSONArray("bumishu");
					for (int z = 0; z < buArray.size(); z++) {
						JSONObject bumishu = (JSONObject) buArray.get(z);
						//布配件中的Goods属性
						Goods pei = new Goods();
						pei.setAccessoriesType(bumishu.getString("accessoriesType"));
						pei.setSaleNumber(bumishu.getDouble("saleNumber"));
						pei.setPinstallSite(bumishu.getString("pinstallSite"));
						pei.setPanzhuangfangshi(bumishu.getString("panzhuangfangshi"));
						pei.setAcc(bumishu.getString("acc"));
						if (jsonObject.get("installCase") != null && jsonObject.getInteger("installCase") != 0) {
							pei.setNumber(2);
						} else {
							pei.setNumber(1);
						}
						merchantsDao.insertpeijian(pei);
						if (goods.getInstallCase() != null && goods.getInstallCase() != 0) {
							Goods_special special = new Goods_special();
							special.setInstallSite(bumishu.getString("installSite"));
							special.setRemark(bumishu.getString("remark"));
							special.setAccessoriesType(bumishu.getString("accessoriesType"));
							special.setWindow(bumishu.getString("window"));
							special.setWide(bumishu.getDouble("wide"));
							special.setHigh(bumishu.getDouble("high"));
							special.setProduction(bumishu.getInteger("production"));
							special.setType(1);

							special.setGoodsId(goods.getGoodsId());
							int goodsIdChild = goods.getGoodsId() * 10 + z;
							special.setGoodsIdChild(goodsIdChild);

							merchantsDao.insertSpecial(special);
						}
						// 存到数据库中并获得id
						Goods_special special = new Goods_special();
						special.setAccId(pei.getGoodsId());
						special.setInstallSite(bumishu.getString("installSite"));
						special.setAccessoriesType(bumishu.getString("accessoriesType"));
						special.setWindow(bumishu.getString("window"));
						special.setWide(bumishu.getDouble("wide"));
						special.setHigh(bumishu.getDouble("high"));
						special.setProduction(bumishu.getInteger("production"));
						special.setType(0);
						special.setGoodsId(goods.getGoodsId());
						int goodsIdChild = goods.getGoodsId() * 10 + z;
						special.setGoodsIdChild(goodsIdChild);
						special.setRemark(bumishu.getString("remark"));
						special.setAccId(pei.getGoodsId());
						merchantsDao.insertSpecial(special);
						JSONArray imgs = (JSONArray) bumishu.get("imgs");
						for (int s = 0; s < imgs.size(); s++) {
							// 把图片存到图片表里
							Map<String, Object> imgmap = new HashMap<>();
							imgmap.put("specialId", special.getSpecialId());
							imgmap.put("img", imgs.get(s));
							imgmap.put("paizhaoType", 0);
							merchantsDao.insertImg(imgmap);
						}
					}
				}
				if (jsonObject.get("shamishu") != null) {
					JSONArray shaarray = jsonObject.getJSONArray("shamishu");
					for (int z = 0; z < shaarray.size(); z++) {
						JSONObject shamishu = (JSONObject) shaarray.get(z);
						// 纱配件中的goods属性存放
						Goods_special special = new Goods_special();
						if (jsonObject.get("installCase") == null || jsonObject.getInteger("installCase") == 0) {
							Goods pei = new Goods();
							pei.setAccessoriesType(shamishu.getString("accessoriesType"));
							pei.setSaleNumber(shamishu.getDouble("saleNumber"));
							pei.setPinstallSite(shamishu.getString("pinstallSite"));
							pei.setNumber(1);
							pei.setPanzhuangfangshi(shamishu.getString("panzhuangfangshi"));
							pei.setAcc(shamishu.getString("acc"));
							merchantsDao.insertpeijian(pei);
							special.setAccId(pei.getGoodsId());
						}
						special.setInstallSite(shamishu.getString("installSite"));
						special.setAccessoriesType(shamishu.getString("accessoriesType"));
						special.setWindow(shamishu.getString("window"));
						special.setWide(shamishu.getDouble("wide"));
						special.setHigh(shamishu.getDouble("high"));
						special.setProduction(shamishu.getInteger("production"));
						special.setType(1);
						special.setGoodsId(goods.getGoodsId());
						int goodsIdChild = goods.getGoodsId() * 10 + z;
						special.setGoodsIdChild(goodsIdChild);
						special.setRemark(shamishu.getString("remark"));
						merchantsDao.insertSpecial(special);
						JSONArray imgs = (JSONArray) shamishu.get("imgs");
						for (int s = 0; s < imgs.size(); s++) {
							// 把图片存到图片表里
							Map<String, Object> imgmap = new HashMap<>();
							imgmap.put("specialId", special.getSpecialId());
							imgmap.put("img", imgs.get(s));
							imgmap.put("paizhaoType", 0);
							merchantsDao.insertImg(imgmap);
						}
					}
				}
				if (jsonObject.get("toumishu") != null) {
					JSONArray touarray = jsonObject.getJSONArray("toumishu");
					for (int z = 0; z < touarray.size(); z++) {
						JSONObject toumishu = (JSONObject) touarray.get(z);
						// 帘头配件Goods属性存放
						Goods pei = new Goods();
						pei.setAccessoriesType(toumishu.getString("accessoriesType"));
						pei.setSaleNumber(toumishu.getDouble("saleNumber"));
						pei.setAcc(toumishu.getString("acc"));
						merchantsDao.insertpeijian(pei);
						// 存到数据库中并获得id
						Goods_special special = new Goods_special();
						special.setWide(toumishu.getDouble("wide"));
						special.setAccId(pei.getGoodsId());
						special.setInstallSite(toumishu.getString("installSite"));
						special.setType(2);
						special.setAccessoriesType(toumishu.getString("accessoriesType"));
						special.setGoodsId(goods.getGoodsId());
						int goodsIdChild = goods.getGoodsId() * 10 + z;
						special.setGoodsIdChild(goodsIdChild);
						special.setRemark(toumishu.getString("remark"));
						merchantsDao.insertSpecial(special);
						if ("不满墙(无窗帘盒)".equals(jsonObject.getString("installSite"))) {
							// num为图片地址
							// 把图片存到图片表里
							Map<String, Object> imgmap = new HashMap<>();
							imgmap.put("specialId", special.getSpecialId());
							imgmap.put("img", toumishu.getString("num"));
							imgmap.put("paizhaoType", 0);
							merchantsDao.insertImg(imgmap);
						}
					}
				}

				// 计算每个商品的安装费
				Map<String, Object> map = jisuanAnzhuan(goods, city);
				merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
				indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
				// 判断结构
				Map<String, Object> send = new HashMap<>();
				send.put("goodsId", goods.getGoodsId());
				send.put("indentId", indent.getIndentId());
				merchantsDao.insertindentGoods(send);
			}
		}
		// 查询电机价格
		// Map<String, Object> dianji = new HashMap<>();
		// dianji.put("type", "电机");
		// dianji.put("shi", shi);
		// Cost_rules dianjiP = merchantsDao.selectAPrice(dianji);
		
		//根据订单属性查找订单的一些价钱费用集合
		Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
		// Map<String, Object> workerPriceMap =
		// merchantsDao.selectCPriceByCity(city, 1);
		//获取安心宝价钱
		Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");// 1为商家
		// merchantsPrice = Math.max(merchantsPrice, (double)
		// merchantsPriceMap.get("installStartingFare"));//费用不低于起步价
		// indentPrice = Math.max(indentPrice, (double)
		// workerPriceMap.get("installStartingFare"));//费用不低于起步价
		//
		// merchantsPrice = Arith.add(merchantsPrice,
		// relievedPrice);//默认将商家价加上安心宝
		//
		// indent.setMerchantsPrice(merchantsPrice);
		// indent.setIndentPrice(indentPrice);
		// Map<String, Object> xiugai = new HashMap<>();
		// xiugai.put("indentId", indent.getIndentId());
		// xiugai.put("merchantsPrice", merchantsPrice);
		// xiugai.put("indentPrice", indentPrice);
		//
		// if (phone != null && !phone.equals(takeGoodsTel))
		// {//取货电话为下单人电话时，认为不需要去其他地方取货，不加取货费用
		// Double takeGoodsPrice = (Double)
		// merchantsPriceMap.get("takeGoodsPrice");//取货价格
		// merchantsPrice = Arith.add(merchantsPrice, takeGoodsPrice);
		// indentPrice = Arith.add(indentPrice, takeGoodsPrice);
		// }
		// // 修改安装订单的价格
		// merchantsDao.updateAIndent(xiugai);
		// 根据订单号查询一些信息，send为返回数据集合
		Map<String, Object> send = merchantsDao.selectIndent(indent.getIndentId());
		if (send.get("baseAddress") == null) {
			send.put("baseAddress", "");
			send.put("detailAddress", "");
		}
		send.put("relievedPrice", relievedPrice);
		Map<String, Object> peifu = merchantsDao.selectPeifu(1);
		// 根据市获取电机每台单价
		Double dianjiPrice = (Double) merchantsPriceMap.get("motorPrice");
		send.put("dianji", (String) peifu.get("beginString") + dianjiPrice + (String) peifu.get("overString"));
		Map<String, Object> beizhu = merchantsDao.selectPeifu(2);
		send.put("jiajiabeizhu", beizhu.get("beginString"));
		Map<String, Object> anxinbao = merchantsDao.selectPeifu(3);
		send.put("anxinbao",
				(String) anxinbao.get("beginString") + relievedPrice + (String) anxinbao.get("overString"));
		send.put("merchantsPrice", 0);
		send.put("indentPrice", 0);
		send.put("dianjiPrice", dianjiPrice);
		// 把订单加到表中 估计这个地方需要推送
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 查询广告
	public BuluResult selectGuanggao() {
		List<String> guanggao = merchantsDao.selectGuanggao();
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(guanggao);
		return buluResult;
	}

	// 注册
	public BuluResult insertMerchants(Merchants merchants) {
		JSONObject map = getAccountMap(merchants.getAccount());
		merchants.setPhone(map.getString("phone"));
		merchants.setPassword(map.getString("password"));
		Date join_date = new Date();
		merchants.setJoin_date(join_date);
		String weiyi = MD5Utils.getUUID();
		merchants.setPassword(MD5Utils.MD5(merchants.getPassword() + weiyi));
		merchants.setWeiyi(weiyi);
		merchantsDao.insertMerchants(merchants);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 检查手机号是否注册
	public BuluResult selectPhone(String phone) {
		Integer result = merchantsDao.selectPhone(phone);
		BuluResult buluResult = new BuluResult();
		if (result == 0) {// 未被注册
			buluResult.setStatus(0);
		} else {// 已注册
			buluResult.setStatus(1);
			buluResult.setMessage("该手机号已被注册!!!");
		}
		return buluResult;
	}

	// 修改密码
	public BuluResult updatePassword(String account) {
		BuluResult buluResult = new BuluResult();
		String weiyi = MD5Utils.getUUID();
		JSONObject jsonObject = getAccountMap(account);
		String phone = jsonObject.getString("phone");
		String password = jsonObject.getString("password");
		if(phone==null||"".equals(phone)||null==password||"".equals(password)){
			buluResult.setStatus(1);
			buluResult.setMessage("请输入有效密码或者长度");
			return buluResult;
		}
		password = MD5Utils.MD5(password + weiyi);
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phone);
		map.put("password", password);
		map.put("weiyi", weiyi);
		merchantsDao.updatePassword(map);
		buluResult.setStatus(0);
		return buluResult;
	}
	
	/**
	 * 对账号和密码进行解密
	 * @param account
	 * @return
	 */
	private JSONObject getAccountMap(String account){
		JSONObject map = new JSONObject();
		try {
			account = AESCipher.aesDecryptString(account, Constant.ENCRYPTKEY);
			map = JSONObject.parseObject(account);
		} catch (Exception e) {
			//logger.error("============加密得到账户和密码时出错============");
			return map;
		} 
		
		return map;
	}
	
	// 登录
	public BuluResult login(String account1, String imei) {
		//返回参数
		BuluResult buluResult = new BuluResult();
		JSONObject object = getAccountMap(account1);
		String phone=object.getString("phone");
		String password=object.getString("password");
		if(null==phone || null==password||"".equals(phone)||"".equals(password)){
			buluResult.setStatus(1);
			buluResult.setMessage("请输入正确的密码或者账号");
			return buluResult;
		}
		
		Integer result = merchantsDao.selectPhone(phone);
		if (result != 0) {
			// 获取拼密码的
			String weiyi = merchantsDao.selectWeiyi(phone);
			password = MD5Utils.MD5(password + weiyi);
			Map<String, Object> map = new HashMap<>();
			map.put("phone", phone);
			map.put("password", password);
			Map<String, Object> send = merchantsDao.selectMerchants(map);
			if (send != null) {
				if ((int) send.get("isDisable") == 0) {
					List<Map<String, Object>> list = merchantsDao.selectDifference((Integer) send.get("merchantsId"));
					if (list != null && list.size() > 0) {
						send.put("haschajia", 1);
					} else {
						send.put("haschajia", 0);
					}
					// 生成一个账号
					String account = "merchants" + send.get("merchantsId").toString();
					send.put("huanxin", account);
					buluResult.setStatus(0);
					buluResult.setData(send);
					String sign = MD5Utils.MD5(String.valueOf(new Date().getTime()));
					send.put("sign", sign);
					JedisUtil.keepSessionIDForApp(sign, String.valueOf(send.get("merchantsId")), 7);
					// 老的iMei
					String databaseImei = merchantsDao.getImeiByMerchantsId((int) send.get("merchantsId"));
					Map<String, Object> param = new HashMap<>();
					param.put("merchantsId", (int) send.get("merchantsId"));
					param.put("imei", imei);
					merchantsDao.updateImeiByMerchantsId(param);
					if (databaseImei != null && !imei.equals(databaseImei)) {// 此次登陆的设备码和上次不一样，发送下线通知
						// 已经有人登陆了 需要注销掉以前用户 然后让新用户登陆,极光推送消息注销老登陆用户
						Map<String, String> typeMap = new HashMap<String, String>();
						typeMap.put("msgType", String.valueOf(5));
//						JpushSendUtil.sendPushMessage2(databaseImei, "提示！你的账号存在风险，一下异地下号", typeMap);
					}
				} else {
					buluResult.setStatus(3);
					buluResult.setMessage("改账号已经被封,如有疑问请咨询人工服务");
				}
			} else {
				buluResult.setStatus(1);
				buluResult.setMessage("密码错误!!!");
			}
		} else {
			buluResult.setStatus(2);
			buluResult.setMessage("手机号未注册!!!");
		}
		return buluResult;
	}

	// 根据前端传的类型查询进行中0测量 1安装 2维修
	public BuluResult selectOngoing(HttpServletRequest request, Integer type) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsId", merchantsId);
		map.put("type", type);
		List<Map<String, Object>> list = merchantsDao.selectOngoing(map);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			for (int a = 0; a < list.size(); a++) {
				list.get(a).put("merchantsPrice",
						Arith.add((Double) list.get(a).get("merchantsPrice"), (Double) list.get(a).get("addPrice")));
				if (type == 1) {
					Integer hasGoods = merchantsDao.selectGoodsNum((Integer) list.get(a).get("indentId"));
					if (hasGoods > 0) {
						list.get(a).put("hasGoods", 1);
					} else {
						list.get(a).put("hasGoods", 0);
					}
				}
				if (list.get(a).get("baseAddress") == null) {
					list.get(a).put("baseAddress", "");
					list.get(a).put("detailAddress", "");
				}
			}
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无订单!!!");
		}
		return buluResult;
	}

	// 查询已完成前端需传一个状态0测量 1安装 2维修
	public BuluResult selectComplete(HttpServletRequest request, Integer type, Integer page) {
		page = 10 * (page - 1);
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsId", merchantsId);
		map.put("type", type);
		map.put("page", page);
		List<Map<String, Object>> list = merchantsDao.selectComplete(map);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			for (int a = 0; a < list.size(); a++) {
				list.get(a).put("merchantsPrice",
						Arith.add((Double) list.get(a).get("merchantsPrice"), (Double) list.get(a).get("addPrice")));
				if (type == 1) {
					Integer hasGoods = merchantsDao.selectGoodsNum((Integer) list.get(a).get("indentId"));
					if (hasGoods > 0) {
						list.get(a).put("hasGoods", 1);
					} else {
						list.get(a).put("hasGoods", 0);
					}
				}
				if (list.get(a).get("baseAddress") == null) {
					list.get(a).put("baseAddress", "");
					list.get(a).put("detailAddress", "");
				}
			}
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无订单!!!");
		}
		return buluResult;
	}

	// 存测量日记
	public BuluResult insertRiji(HttpServletRequest request, String name, String phone, String province, String city,
			String area, String address,String remark,String baseAddress, String detailAddress, String takeGoodsTel,String isNeedTakeGoods) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Customer_address customer_address = new Customer_address();
		customer_address.setProvince(province);
		customer_address.setCity(city);
		customer_address.setArea(area);

		// 查询该区对应的code
		String areaCode = getCodeByCityAndArea(city, area);
		//logger.error("areaCode==" + areaCode);
		String provinceCode = workerDao.selectProvinceCodeForWorker(province);
		String cityCode = workerDao.selectCityCodeForWorker(city);
		String workerSpaceCodeStr = provinceCode + "/" + cityCode;
		customer_address.setCuAddressCodeStr(workerSpaceCodeStr);
		customer_address.setAreaCode(areaCode);
		customer_address.setAddress(address);
		customer_address.setName(name);
		customer_address.setPhone(phone);
		merchantsDao.addNewCustomer_address(customer_address);
		Indent indent = new Indent();
		indent.setCustomerId(merchantsId);
		indent.setCuAdId(customer_address.getCuAdId());
		Date beginTime = new Date();
		indent.setBeginTime(beginTime);
		indent.setIndentType(1);//代表测量日记
		//indent.setOrderId(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId));
		if (isNeedTakeGoods != null && "1".equals(isNeedTakeGoods)) {//需要取货
			indent.setBaseAddress(baseAddress);
			indent.setDetailAddress(detailAddress);
			indent.setTakeGoodsTel(takeGoodsTel);
		}else{
			indent.setBaseAddress("无");
			indent.setDetailAddress("无");
			indent.setTakeGoodsTel("无");
		}
		indent.setRemark(remark);
		indent.setIsNeedTakeGoods(isNeedTakeGoods != null ? Integer.parseInt(isNeedTakeGoods):0);//测量单都设置为不需要取货
		merchantsDao.addNewIndentOfMeasure(indent);
		//logger.error(indent.getIndentId());
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(indent.getIndentId());
		return buluResult;
	}

	// 查测量日记
	public BuluResult selectRiji(HttpServletRequest request, Integer page) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		page = 10 * (page - 1);
		Map<String, Object> map = new HashMap<>();
		map.put("page", page);
		map.put("merchantsId", merchantsId);
		// 查询类型为日记 id为登录人id
		List<Map<String, Object>> list = merchantsDao.selectRiji(map);
		for (Map<String, Object> map2 : list) {
			//logger.error("数据库查询到的日记内容==" + map2.toString());
		}
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			// 需要判断一下状态 什么鬼
			for (int a = 0; a < list.size(); a++) {
				// 查询有多少个商品
				List<Integer> goodsGeshu = merchantsDao.selectGoodsId((Integer) list.get(a).get("indentId"));
				if (goodsGeshu != null && goodsGeshu.size() > 0) {
					Integer tianxie = merchantsDao.selectTianxie((Integer) list.get(a).get("indentId"));
					if (goodsGeshu.size() == tianxie) {
						list.get(a).put("hasData", 1);
					}
				} else {
					list.get(a).put("hasData", 0);
				}

			}
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setData("暂时没有数据!!!");
		}
		return buluResult;
	}

	// 根据手机号查询头像
	public BuluResult selectHeadImg(String phone) {
		String img = merchantsDao.selectHeadImg(phone);
		BuluResult buluResult = new BuluResult();
		if (img != null) {
			buluResult.setStatus(0);
			buluResult.setData(img);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无头像!!!");
		}
		return buluResult;
	}

	/**
	 * @indentId 订单ID
	 * @goods 需要的部件
	 * @bumishu
	 * @shamishu 订单ID
	 * @toumishu 订单ID
	 * @imgs 订单ID
	 * 
	 */
	// 给订单添加商品
	public BuluResult insertGoods(Integer indentId, Goods goods, String bumishu, String shamishu, String toumishu,
			String imgs, String finishShade) {
		/**
		 * 如果toumishu等于null 则为没有帘头
		 */
		if (toumishu != null) {
			goods.setShadeHead(1);
		}
		goods.setIstianxie(1);
		// 把goods存到商品表中并获取id
		merchantsDao.insertGoods(goods);
		/*
		 * if (goods.getType() == 1) {// 成品帘 // 为成品帘上传的图片 if (imgs != null) {
		 * JSONArray jsonArrayCpl = JSONObject.parseArray(imgs); for (int g = 0;
		 * g < jsonArrayCpl.size(); g++) { Map<String, Object> cpl = new
		 * HashMap<>(); cpl.put("goodsId", goods.getGoodsId()); cpl.put("img",
		 * jsonArrayCpl.getString(g)); workerDao.insertChengPinLianImg(cpl); } }
		 * }
		 */
		if (finishShade != null) {//成品帘
			JSONArray jsonArray = JSONArray.parseArray(finishShade);
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				// 成品帘配件
				Goods pei = new Goods();
				pei.setPinstallSite(jsonObject.getString("pinstallSite"));
				merchantsDao.insertpeijian(pei);
				
				Goods_special special = new Goods_special();
				special.setAccId(pei.getGoodsId());
				special.setInstallSite(jsonObject.getString("installSite"));
				special.setAccessoriesType(jsonObject.getString("accessoriesType"));
				special.setWindow(jsonObject.getString("window"));
				special.setWide(jsonObject.getDouble("wide"));
				special.setHigh(jsonObject.getDouble("high"));
				special.setGoodsId(goods.getGoodsId());
				int goodsIdChild = goods.getGoodsId() * 10 + i;
				special.setGoodsIdChild(goodsIdChild);
				special.setRemark(jsonObject.getString("remark"));
				special.setType(3);
				merchantsDao.insertSpecial(special);
				if (null != jsonObject.get("imgs") && !"".equals(jsonObject.get("imgs"))) {
					JSONArray imgsB = (JSONArray) jsonObject.get("imgs");
					for (int s = 0; s < imgsB.size(); s++) {
						// 把图片存到图片表里
						Map<String, Object> imgmap = new HashMap<>();
						imgmap.put("specialId", special.getSpecialId());
						imgmap.put("img", imgsB.get(s));
						imgmap.put("paizhaoType", 0);
						merchantsDao.insertImg(imgmap);
					}
				}

			}
		}
		if (bumishu != null) {//布艺帘布尺寸
			JSONArray jsonArray1 = JSONArray.parseArray(bumishu);
			for (int i = 0; i < jsonArray1.size(); i++) {
				JSONObject jsonObject = (JSONObject) jsonArray1.get(i);
				// 布配件
				Goods pei = new Goods();
				pei.setAccessoriesType(jsonObject.getString("accessoriesType"));
				pei.setSaleNumber(jsonObject.getDouble("saleNumber"));
				pei.setPinstallSite(jsonObject.getString("pinstallSite"));
				if (goods.getInstallCase() != null && goods.getInstallCase() != 0) { ////布纱安装情况:1一致 0不一致
					pei.setNumber(2);
				} else {
					pei.setNumber(1);
				}
				pei.setPanzhuangfangshi(jsonObject.getString("panzhuangfangshi"));
				pei.setAcc(jsonObject.getString("acc"));
				merchantsDao.insertpeijian(pei);
				
				
				if (goods.getInstallCase() != null && goods.getInstallCase() == 1) {// 布纱同一位置安装
					Goods_special special = new Goods_special();
//					special.setAccId(pei.getGoodsId());
					special.setInstallSite(jsonObject.getString("installSite"));
					special.setAccessoriesType(jsonObject.getString("accessoriesType"));
					special.setWindow(jsonObject.getString("window"));
					special.setWide(jsonObject.getDouble("wide"));
					special.setHigh(jsonObject.getDouble("high"));
					special.setProduction(jsonObject.getInteger("production"));
					special.setGoodsId(goods.getGoodsId());
					int goodsIdChild = goods.getGoodsId() * 10 + i;
					special.setGoodsIdChild(goodsIdChild);
					special.setRemark(jsonObject.getString("remark"));
					special.setType(1);
					merchantsDao.insertSpecial(special);
				}
				// 存到数据库中并获得id
				Goods_special special = new Goods_special();
				special.setAccId(pei.getGoodsId());
				special.setInstallSite(jsonObject.getString("installSite"));
				special.setAccessoriesType(jsonObject.getString("accessoriesType"));
				special.setWindow(jsonObject.getString("window"));
				special.setWide(jsonObject.getDouble("wide"));
				special.setHigh(jsonObject.getDouble("high"));
				special.setProduction(jsonObject.getInteger("production"));
				special.setType(0);
				special.setGoodsId(goods.getGoodsId());
				int goodsIdChild = goods.getGoodsId() * 10 + i;
				special.setGoodsIdChild(goodsIdChild);
				special.setRemark(jsonObject.getString("remark"));
				merchantsDao.insertSpecial(special);
				
				if (!"".equals(jsonObject.get("imgs")) && null != jsonObject.get("imgs")) {
					JSONArray imgsB = (JSONArray) jsonObject.get("imgs");
					for (int s = 0; s < imgsB.size(); s++) {
						// 把图片存到图片表里
						Map<String, Object> imgmap = new HashMap<>();
						imgmap.put("specialId", special.getSpecialId());
						imgmap.put("img", imgsB.get(s));
						imgmap.put("paizhaoType", 0);
						merchantsDao.insertImg(imgmap);
					}
				}
			}
		}
		if (shamishu != null) {//布艺帘纱尺寸
			// 不为空证明有纱
			JSONArray jsonArray1 = JSONArray.parseArray(shamishu);
			for (int a = 0; a < jsonArray1.size(); a++) {
				JSONObject jsonObject = (JSONObject) jsonArray1.get(a);
				// 存到数据库中并获得id
				Goods_special special = new Goods_special();
				// 纱配件
				if (goods.getInstallCase() == null || goods.getInstallCase() == 0) {
					Goods pei = new Goods();
					pei.setAccessoriesType(jsonObject.getString("accessoriesType"));
					pei.setSaleNumber(jsonObject.getDouble("saleNumber"));
					pei.setPinstallSite(jsonObject.getString("pinstallSite"));
					pei.setNumber(1);
					pei.setPanzhuangfangshi(jsonObject.getString("panzhuangfangshi"));
					pei.setAcc(jsonObject.getString("acc"));
					merchantsDao.insertpeijian(pei);
					special.setAccId(pei.getGoodsId());
				}
				special.setInstallSite(jsonObject.getString("installSite"));
				special.setAccessoriesType(jsonObject.getString("accessoriesType"));
				special.setWindow(jsonObject.getString("window"));
				special.setWide(jsonObject.getDouble("wide"));
				special.setHigh(jsonObject.getDouble("high"));
				special.setProduction(jsonObject.getInteger("production"));
				special.setType(1);
				special.setGoodsId(goods.getGoodsId());
				int goodsIdChild = goods.getGoodsId() * 10 + a;
				special.setGoodsIdChild(goodsIdChild);
				special.setRemark(jsonObject.getString("remark"));
				merchantsDao.insertSpecial(special);
				if (!"".equals(jsonObject.get("imgs")) && null != jsonObject.get("imgs")) {
					JSONArray imgsB = (JSONArray) jsonObject.get("imgs");
					for (int s = 0; s < imgsB.size(); s++) {
						// 把图片存到图片表里
						Map<String, Object> imgmap = new HashMap<>();
						imgmap.put("specialId", special.getSpecialId());
						imgmap.put("img", imgsB.get(s));
						imgmap.put("paizhaoType", 0);
						merchantsDao.insertImg(imgmap);
					}
				}
			}
		}
		if (toumishu != null) {//布艺帘帘头
			// 不为空证明有帘头
			JSONArray jsonArray1 = JSONArray.parseArray(toumishu);
			for (int a = 0; a < jsonArray1.size(); a++) {
				JSONObject jsonObject = (JSONObject) jsonArray1.get(a);
				// 帘头配件
				Goods pei = new Goods();
				pei.setAccessoriesType(jsonObject.getString("accessoriesType"));
				pei.setSaleNumber(jsonObject.getDouble("saleNumber"));
				pei.setAcc(jsonObject.getString("acc"));
				pei.setParsOfPars(jsonObject.getString("parsOfPars"));
				merchantsDao.insertpeijian(pei);
				// 存到数据库中并获得id
				Goods_special special = new Goods_special();
				special.setWide(jsonObject.getDouble("wide"));
				special.setAccId(pei.getGoodsId());
				special.setInstallSite(jsonObject.getString("installSite"));
				special.setType(2);
				special.setAccessoriesType(jsonObject.getString("accessoriesType"));
				special.setGoodsId(goods.getGoodsId());
				int goodsIdChild = goods.getGoodsId() * 10 + a;
				special.setGoodsIdChild(goodsIdChild);
				special.setRemark(jsonObject.getString("remark"));
				merchantsDao.insertSpecial(special);
				
				if ("不满墙(无窗帘盒)".equals(jsonObject.getString("installSite"))) {
					// num为图片地址
					// 把图片存到图片表里
					Map<String, Object> imgmap = new HashMap<>();
					imgmap.put("specialId", special.getSpecialId());
					imgmap.put("img", jsonObject.getString("num"));
					imgmap.put("paizhaoType", 0);
					merchantsDao.insertImg(imgmap);
				}
			}
		}

		// 把商品号与订单号关联一下
		Map<String, Object> send = new HashMap<>();
		send.put("goodsId", goods.getGoodsId());
		send.put("indentId", indentId);
		merchantsDao.insertindentGoods(send);
		// 根据订单号查询订单类型
		Integer indentType = merchantsDao.selectIndentType(indentId);
		if (indentType == 3) {
			// 根据订单号查询市
			String city = merchantsDao.selectIndentCity(indentId);
			// 获取市

			// 根据订单号查询所有商品,0代表未删除状态
			List<Goods> list = merchantsDao.selectAllGoods(indentId, 0);

			Double merchantsPrice = 0.0;
			Double indentPrice = 0.0;
			Double workerRealPrice = 0.0;
			Double merchantsRealPrice = 0.0;
			//每次给订单添加商品都要重新计算订单的总价、真实价格
			if (list.size() > 0) {
				for (int a = 0; a < list.size(); a++) {
					Map<String, Object> map = jisuanAnzhuan(list.get(a), city);
					merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
					indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
				}
				workerRealPrice = indentPrice;
				merchantsRealPrice = merchantsPrice;
				Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
				Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity(city, 0);
				
				merchantsPrice = Math.max(merchantsPrice, (Double) merchantsPriceMap.get("installStartingFare"));
				indentPrice = Math.max(indentPrice, (Double) workerPriceMap.get("installStartingFare"));
				// 判断是否需要取货
				Integer isNeedTakeGoods = merchantsDao.selectIsNeedTakeGoods(indentId);
				if (isNeedTakeGoods != null && isNeedTakeGoods == 1) {
					merchantsPrice = Arith.add(merchantsPrice, (double) merchantsPriceMap.get("takeGoodsPrice"));
					indentPrice = Arith.add(indentPrice, (double) workerPriceMap.get("takeGoodsPrice"));
				}
				/*
				 * if (list.size() > 0) { merchantsPrice =
				 * Arith.add(merchantsPrice, (double)
				 * merchantsPriceMap.get("relievedPrice")); }
				 */
			}
			//更新商品的总价、真是价格
			Integer goodsNum = workerDao.selectGoodsNum(indentId);
			Map<String, Object> charu = new HashMap<>();
			charu.put("indentId", indentId);
			charu.put("merchantsPrice", merchantsPrice);
			charu.put("indentPrice", indentPrice);
			charu.put("workerRealPrice", workerRealPrice);
			charu.put("merchantsRealPrice", merchantsRealPrice);
			charu.put("roomNumB", goodsNum==null?0:goodsNum);
			merchantsDao.updateindentPrice(charu);
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询提现明细
	public BuluResult selectMingxi(HttpServletRequest request,Integer page) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String,Object> map = new HashMap<>();
		//他们传过来的page初始值为1
		page = 10 * ((page==null?1:page) - 1);//计算每一页从第几条记录开始查询
		map.put("page", page);
		map.put("merchantsId", merchantsId);
		List<Map<String, Object>> list = merchantsDao.selectMingxi(map);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("没有提现数据!!!");
		}
		return buluResult;
	}

	// 查询进行中角标
	public BuluResult selectJiaobiao(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsId", merchantsId);
		map.put("type", 0);
		List<Map<String, Object>> list = merchantsDao.selectOngoing(map);
		Map<String, Object> map1 = new HashMap<>();
		map1.put("merchantsId", merchantsId);
		map1.put("type", 1);
		List<Map<String, Object>> list2 = merchantsDao.selectOngoing(map1);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("merchantsId", merchantsId);
		map2.put("type", 2);
		List<Map<String, Object>> list3 = merchantsDao.selectOngoing(map2);
		Map<String, Object> send = new HashMap<>();
		if (list != null) {
			send.put("celiang", list.size());
		}
		if (list2 != null) {
			send.put("anzhuang", list2.size());
		}
		if (list3 != null) {
			send.put("weixiu", list3.size());
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 根据市查询维修费和维修备注
	public BuluResult selectWeixiu(String city, String areaCode) {
		BuluResult buluResult = theAreaIsDredge(city, areaCode);
		if (buluResult.getStatus() == 0) {
			Map<String, Object> send = new HashMap<>();
			Map<String, Object> oldMap = (Map<String, Object>) buluResult.getData();
			if (((int) (oldMap.get("theAreaIsDredge")) == 1)) {// 区域已开通
				int territoryId = merchantsDao.selectTerritoryIdByCity(city);
				Map<String, Object> map = merchantsDao.selectWeixiu(territoryId);
				// 查询每次加价价格
				if (map != null) {
					Double premium = merchantsDao.selectPremium();
					send.put("premium", premium);
					send.put("beizhu", (String) map.get("beginString") + (Double) map.get("repairStartingFare")
							+ (String) map.get("overString"));

					send.put("qibujia", map.get("repairStartingFare"));

					send.putAll(oldMap);
					send.put("takeGoodsCost", oldMap.get("takeGoodsCost"));
					buluResult.setStatus(0);
					buluResult.setData(send);
					return buluResult;
				}
			}
			send.putAll(oldMap);
			buluResult.setData(send);
		}
		return buluResult;
	}

	// 查询工人接单后商家取消应扣款
	public BuluResult selectYingkou(Integer indentId) {
		BuluResult buluResult = new BuluResult();
		Map<String, Object> map = merchantsDao.selectIndent(indentId);
		int status = (int) map.get("status");
		int territoryId = merchantsDao.selectIndentCityTerritoryId(indentId);
		Map<String, Double> punishMap = merchantsDao.selectBaifenbi(territoryId);
		if (status == 1) {// 工人接单未出发，商家扣除20
			buluResult.setData(punishMap.get("punishWorker"));
		} else if (status == 5) {// 工人接单并出发，商家扣除50
			buluResult.setData(punishMap.get("punishClient"));
		} else if (status == 0) { // 工人没有接单，商家不扣钱
			buluResult.setData(0);
		}
		buluResult.setStatus(0);
		return buluResult;
	}

	// 取消订单
	public BuluResult deleteIndent(HttpServletRequest request, Integer indentId) {
		//准备返回参数
		BuluResult buluResult = new BuluResult();
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		//找到该订单状态
		Integer status = merchantsDao.selectStatus(indentId);
		//判断订单支付的状态根据状态处理不同的业务
		if(status == 4){//未支付
			int result = updateIndentStatus(indentId);
			buluResult.setStatus(result>0?0:1);
			buluResult.setMessage(result>0?"取消订单成功":"操作失败,请稍后重试");
		}else if(status==0||status==1||status==5 ){//支付过
			int result = updateIndentStatus(indentId);
			if(result>0){
				//商家钱包情况
				Map<String, Object> map2 = merchantsDao.selectMerchantsWallet(merchantsId);
				// 找到该订单花的总金额
				Map<String, Double> merchantsPrice = merchantsDao.selectMerchantsPrice(indentId);
				//准备返回给商家的钱
				Double wallet = 0.00;
				//准备返回给工人的钱
				Double Toworker = 0.00;
				if (status == 0) {
					wallet = Arith.add(merchantsPrice.get("merchantsPrice"), merchantsPrice.get("addPrice"));
				} else {
					// 工人接单了需计算扣钱的金额和需要返给商家的钱数
					int territoryId = merchantsDao.selectIndentCityTerritoryId(indentId);
					Map<String, Double> punishMap = merchantsDao.selectBaifenbi(territoryId);
					if (status == 1) {
						wallet = Arith.sub(Arith.add(merchantsPrice.get("merchantsPrice"), merchantsPrice.get("addPrice")),
								punishMap.get("punishWorker"));
						Toworker = punishMap.get("punishWorker");
					} else if (status == 5) {
						wallet = Arith.sub(Arith.add(merchantsPrice.get("merchantsPrice"), merchantsPrice.get("addPrice")),
								punishMap.get("punishClient"));
						Toworker =punishMap.get("punishClient");
					}
					//查找工人的钱包
					Map<String,Object> param = merchantsDao.selectIndent(indentId);
					Double workerWallet = workerDao.selectWallet((Integer)param.get("workerId"));
					workerWallet = Arith.add(workerWallet, Toworker);
					//给工人钱包加上商家取消扣除的钱
					Map<String, Object> send = new HashMap<>();
					send.put("workerId", (Integer)param.get("workerId"));
					send.put("wallet", workerWallet);
					//更新工人钱包
					workerDao.updateWalletComple(send);
					// 将本次钱包余额记录插入数据库  2017-5-5XGH
					/*walletRecordService.insertWalletRecord((Integer)param.get("workerId"), indentId, 2, Toworker, 
					 		null,null, Toworker, null, 4, 1, "商家或者个人取消订单工人获取规定罚款", 0, "余额增加");*/
					workerWalletRecordService.insertWorkerWalletRecord((Integer)param.get("workerId"), indentId, 2,
							Toworker, null, null, Toworker, null, null,null, WorkerType.MERCHANTS_CANCLE.getIndex(), 1, "商家或者个人取消订单工人获取规定罚款", 0, "钱包余额变动");
					//merchantswalletRecordService
				}
				//更新商家的钱包
				Map<String, Object> map = new HashMap<>();
				map.put("merchantsId", merchantsId);
				map.put("wallet", wallet);
				int update = merchantsDao.updateWallet(map);
				// 将本次钱包余额记录插入数据库 2017-5-8   XGH
				if(update>0){
					/*merchantsId, indentId, merchantsType,
					mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
					walletRecharge,walletWithdrawals, 
					type,status,remark, isDelete, method*/
					merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
							(Integer)map2.get("type"), merchantsPrice.get("merchantsPrice"), merchantsPrice.get("addPrice"), Toworker, wallet, Toworker, 
							null, null, TypeOfIndent.CANCEL.getIndex(), 1, "商家或者个人取消订单",null, 0, PayMethod.BALABCEPAY.getMethod());
					
				}
				/*walletRecordService.insertWalletRecord(merchantsId, indentId, (Integer)map2.get("type"), merchantsPrice.get("merchantsPrice"), 
						merchantsPrice.get("addPrice"),Toworker, wallet, Toworker, 4, 1, "商家或者个人取消订单", 0, "钱包余额交易");*/
				
			}
			buluResult.setStatus(result>0?0:1);
			buluResult.setMessage(result>0?"订单取消成功":"订单取消失败,请确认订单为有效订单");
		}
		return buluResult;
	}
	
	private int updateIndentStatus(Integer indentId){
		// 修改订单状态 为删除状态
		int result = merchantsDao.updateIndentStatus(indentId);
		if(result > 0 ){
			//如果是测量日记转下的安装订单需要解绑订单关系 2017-5-4 xiaGuanghui修改
			List<Integer> listGoodsId = merchantsDao.selectGoodsId(indentId);
			if(null != listGoodsId && listGoodsId.size()>0){//说明该订单下存在有效商品
				for(int a =0;a<listGoodsId.size();a++){
					Integer goodsId = listGoodsId.get(a);
					Goods goods = merchantsDao.selectGoodxinxi(goodsId);
					if(1==goods.getHasInstall()){//说明有测量日记订单转化为安装订单
						//删除和安装订单的关系
						merchantsDao.deleteGoodsAndIndent(goodsId,indentId);
						//将其变为未转化过
						merchantsDao.updateGoodsHasInstall(goodsId);
					}else{
						//删除和订单的关系
						merchantsDao.deleteGoodsAndIndent(goodsId,indentId);
						//订单旗下所有的商品也要标志为删除
						merchantsDao.deleteGoodsId(goodsId);
					}
				}
			}
		}
		return result;
	}
	
	// 查询备注
	public BuluResult selectBeizhu(String city) {
		Map<String, Object> send = new HashMap<>();
		// 查询安心宝价格
		Double relievedPrice = merchantsDao.selectAnxinbao(city);
		send.put("relievedPrice", relievedPrice);
		// 查询每次加价价格
		Double premium = merchantsDao.selectPremium();
		send.put("premium", premium);
		// 根据市获取加价备注
		Map<String, Object> beizhu = merchantsDao.selectPeifu(2);
		send.put("jiajiabeizhu", beizhu.get("beginString"));
		Map<String, Object> anxinbao = merchantsDao.selectPeifu(3);
		send.put("anxinbao",
				(String) anxinbao.get("beginString") + relievedPrice + (String) anxinbao.get("overString"));
		BuluResult buluResult = new BuluResult();
		buluResult.setData(send);
		buluResult.setStatus(0);
		return buluResult;
	}

	// 添加对工人的评价
	public BuluResult insertEvaluation(Integer star, String content, HttpServletRequest request, String imgs,
			Integer indentId) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Evaluation evaluation = new Evaluation();
		evaluation.setContent(content);
		evaluation.setStar(star);
		evaluation.setType(4);
		evaluation.setCustomerId(merchantsId);
		evaluation.setIndentId(indentId);
		// 根据订单id查询工人id
		Integer workerId = merchantsDao.selectWorker(indentId);
		evaluation.setWorkerId(workerId);
		evaluation.setEvaTime(new Date());
		merchantsDao.insertEvaluation(evaluation);
		merchantsDao.updateStatus(indentId);
		if (imgs != null) {
			JSONArray jsonArray = JSONArray.parseArray(imgs);
			for (int a = 0; a < jsonArray.size(); a++) {
				// 存图片
				Map<String, Object> map = new HashMap<>();
				map.put("evaluationId", evaluation.getEvaluationId());
				map.put("img", jsonArray.get(a));
				merchantsDao.insertTupian(map);
			}
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 删除测量日记
	public BuluResult deleteRiji(Integer indentId) {
		// 删除日记update indent set status = 7 where indentId=#{indentId}
		merchantsDao.deleteGoods(indentId);
		// 获得商品
		List<Integer> list = merchantsDao.selectGoodsId(indentId);
		for (int a = 0; a < list.size(); a++) {
			Goods goods = merchantsDao.selectGoodxinxi(list.get(a));
			if(goods.getHasInstall()==0){//日记下的商品未下安装订单,则此商品可以标志为删除
				//update goods set isDeleted=1 where goodsId=#{goodsId}
				merchantsDao.deleteGoodsId(list.get(a));
			}
		}
		//解绑该测量日记和旗下的所有商品的关系update goods_indent set isDeleted = 1 where indentId=#{indentId}
		merchantsDao.deleteGuangxi(indentId);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询个人信息
	public BuluResult selectGeren(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Merchants merchants = merchantsDao.selectGeren(merchantsId);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(merchants);
		return buluResult;
	}

	// 修改头像
	public BuluResult updateHeadImg(HttpServletRequest request, String headImg) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsId", merchantsId);
		map.put("headImg", headImg);
		merchantsDao.updateHeadImg(map);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 修改信息
	public BuluResult updateMerchants(Merchants merchants) {
		merchantsDao.updateMerchants(merchants);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 根据订单号获取商品
	public BuluResult selectGoods(Integer indentId) {
		// 根据订单号查询市
		String city = merchantsDao.selectIndentCity(indentId);
		// 获取市
		Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
		List<Map<String, Object>> list = merchantsDao.selectGoods(indentId);
		List<Goods> goodss = merchantsDao.selectGoodsPojo(indentId);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			for (int a = 0; a < list.size(); a++) {
				if (list.get(a).get("sampleId") != null) {
					String sampleImg = workerDao.selectSampleImg((Integer) list.get(a).get("sampleId"));
					list.get(a).put("sampleImg", sampleImg);
				}
				if (list.get(a).get("locationId") != null) {
					String locationContent = workerDao.selectLocationConent((Integer) list.get(a).get("locationId"));
					list.get(a).put("locationContent", locationContent);
				} else {
					list.get(a).put("locationContent", list.get(a).get("otherRoom"));
				}
				if((Integer)indentMap.get("status")!=2){
					if ((Integer) list.get(a).get("istianxie") != 0) {
						Map<String, Object> map = jisuanAnzhuan(goodss.get(a), city);
						list.get(a).put("installPrice", map.get("merchantsPrice"));
					} else {
						list.get(a).put("installPrice", 0.0);
					}
				}
				//logger.error("=================================" + JSONObject.toJSONString(list) + "");
				if ((Integer) list.get(a).get("type") == 0) {// 布艺帘
					// 判断是什么结构
					if ((Integer) list.get(a).get("structure") == 0) {// 单布
						// 查询布有几个尺寸好吧
						Integer buchicun = factoryDao.selectGoodsBu((Integer) list.get(a).get("goodsId"));
						if (buchicun == 0 || buchicun == 1) {
							// 根据商品号查询出尺寸
							Map<String, Object> map = factoryDao
									.selectGoodsBuchicun((Integer) list.get(a).get("goodsId"));
							list.get(a).put("buwide", map.get("wide"));
							list.get(a).put("buhigh", map.get("high"));
							// 判断是否有帘头
							if ((Integer) list.get(a).get("shadeHead") == 1) {
								list.get(a).put("touwide",
										factoryDao.selectGoodsTouchicun((Integer) list.get(a).get("goodsId")));
							}
							list.get(a).put("special", 0);
						} else {
							list.get(a).put("special", 1);
						}
					} else if ((Integer) list.get(a).get("structure") == 1) {// 单纱
						// 查询纱有几个尺寸
						Integer shachicun = factoryDao.selectGoodsSha((Integer) list.get(a).get("goodsId"));
						if (shachicun == 0 || shachicun == 1) {
							// 根据商品号查询出尺寸
							Map<String, Object> map = factoryDao
									.selectGoodsShachicun((Integer) list.get(a).get("goodsId"));
							list.get(a).put("shawide", map.get("wide"));
							list.get(a).put("shahigh", map.get("high"));
							list.get(a).put("special", 0);
						} else {
							list.get(a).put("special", 1);
						}
					} else {// 布加纱
							// 查询布有几个尺寸
						Integer buchicun = factoryDao.selectGoodsBu((Integer) list.get(a).get("goodsId"));
						if (buchicun == 0 || buchicun == 1) {
							// 查询纱有几个尺寸
							Integer shachicun = factoryDao.selectGoodsSha((Integer) list.get(a).get("goodsId"));
							if (shachicun == 0 || shachicun == 1) {
								// 根据商品号查询出布尺寸
								Map<String, Object> map = factoryDao
										.selectGoodsBuchicun((Integer) list.get(a).get("goodsId"));
								list.get(a).put("buwide", map.get("wide"));
								list.get(a).put("buhigh", map.get("high"));
								// 根据商品号查询出纱尺寸
								Map<String, Object> map1 = factoryDao
										.selectGoodsShachicun((Integer) list.get(a).get("goodsId"));
								list.get(a).put("shawide", map1.get("wide"));
								list.get(a).put("shahigh", map1.get("high"));
								// 判断是否有帘头
								if ((Integer) list.get(a).get("shadeHead") == 1) {
									list.get(a).put("touwide",
											factoryDao.selectGoodsTouchicun((Integer) list.get(a).get("goodsId")));
								}
								list.get(a).put("special", 0);
							} else {
								list.get(a).put("special", 1);
							}
						} else {
							list.get(a).put("special", 1);
						}
					}
				} else if ((Integer) list.get(a).get("type") == 1) {// 成品帘
					int flag = (int) list.get(a).get("istianxie");
					if (flag == 1) {
						Integer finishNum = factoryDao.selectGoodsFinish((Integer) list.get(a).get("goodsId"));
						if (finishNum == 1) {
							Map<String, Object> finishMap = factoryDao
									.selectFinishChicun((Integer) list.get(a).get("goodsId"));
							list.get(a).put("window", finishMap.get("window"));
							list.get(a).put("accessoriesType", finishMap.get("accessoriesType"));
							Goods goods = merchantsDao.selectGoodxinxi((Integer) finishMap.get("accId"));
							list.get(a).put("pinstallSite", goods.getPinstallSite());
							list.get(a).put("wide", finishMap.get("wide"));
							list.get(a).put("high", finishMap.get("high"));
							list.get(a).put("special", 0);
							List<String> imgs = merchantsDao.selectChengpinImgs((Integer) finishMap.get("specialId"));
							list.get(a).put("imgs", imgs);
						} else if (finishNum > 1) {
							list.get(a).put("special", 1);
						}
					}
					// 查询成品帘测量图片
					// List<String> imgs =
					// merchantsDao.selectChengpinImgs((Integer)
					// list.get(a).get("goodsId"));
					// list.get(a).put("imgs", imgs);
					// 根据成品帘类型id查询出类型
					String fptBody = factoryDao.selectChnegpin((Integer) list.get(a).get("fptId"));
					list.get(a).put("fptBody", fptBody);
				}
			}
			buluResult.setStatus(0);
			//logger.error("返回数据的格式:" + JSONObject.toJSONString(list));
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无商品!!!");
		}
		return buluResult;
	}

	// 查询地址
	public BuluResult selectAddress(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		List<Map<String, Object>> list = merchantsDao.selectAddress(merchantsId);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无数据");
		}
		return buluResult;
	}

	// 添加地址
	public BuluResult insertAddress(HttpServletRequest request, Customer_address address) {
		String sign = request.getParameter("sign");

		String areaCode = getCodeByCityAndArea(address.getCity(), address.getArea());
		address.setAreaCode(areaCode);

		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		address.setCustomerId(merchantsId);
		merchantsDao.insertAddress(address);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 删除地址
	public BuluResult deleteAddress(Integer cuAdId) {
		merchantsDao.deleteAddress(cuAdId);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 编辑地址
	public BuluResult updateAddress(Customer_address address,String baseAddress,String detailAddress,
			String takeGoodsTel,String remark) {
		merchantsDao.updateAddress(address);
		Map<String, Object> map = new HashMap<>();
		map.put("baseAddress", baseAddress == null ? "无" : baseAddress);
		map.put("detailAddress", detailAddress == null ? "无" : detailAddress);
		map.put("takeGoodsTel", takeGoodsTel == null ? "无" : takeGoodsTel);
		map.put("remark", remark);
		map.put("cuAdId", address.getCuAdId());
		merchantsDao.updateTakeGoodsAddress(map);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 设为默认
	public BuluResult setDefault(HttpServletRequest request, Integer cuAdId) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 查询原来的默认
		Integer YcuAdId = merchantsDao.selectDefault(merchantsId);
		if (YcuAdId != null) {
			// 修改为不是默认
			Map<String, Object> map = new HashMap<>();
			map.put("cuAdId", YcuAdId);
			map.put("status", 0);
			merchantsDao.updateDefault(map);
			map.put("cuAdId", cuAdId);
			map.put("status", 1);
			merchantsDao.updateDefault(map);
		} else {
			Map<String, Object> map = new HashMap<>();
			map.put("cuAdId", cuAdId);
			map.put("status", 1);
			merchantsDao.updateDefault(map);
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询钱包
	public BuluResult selectWallet(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map = merchantsDao.selectWallet(merchantsId);
		// 查询默认银行卡信息
		Map<String, Object> map2 = merchantsDao.selectDefultBank(merchantsId);
		if (map2 != null) {
			map.put("alipayNum", map2.get("alipayNum"));
			map.put("boundBank", map2.get("alipayNum"));
		}else{
			map.put("alipayNum", "无");
			map.put("boundBank", "无");
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		//logger.error(map.toString());
		buluResult.setData(map);
		return buluResult;
	}

	// 意见反馈
	public BuluResult insertWenti(HttpServletRequest request, String problemCount, String imgs) {
		String sign = (String) request.getParameter("sign");
		if (sign != null) {
			Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
			Problem problem = new Problem();
			problem.setProblemCount(problemCount);
			problem.setTypeId(merchantsId);
			problem.setAppId(5);
			Date problemTime = new Date();
			problem.setProblemTime(problemTime);
			workerDao.insertProblem(problem);
			if (imgs != null) {
				JSONArray jsonimgs = JSONArray.parseArray(imgs);
				for (int a = 0; a < jsonimgs.size(); a++) {
					Map<String, Object> map = new HashMap<>();
					map.put("img", jsonimgs.get(a));
					map.put("problemId", problem.getProblemId());
					workerDao.insertWenti(map);
				}
			}
		} else {
			Problem problem = new Problem();
			problem.setProblemCount(problemCount);
			problem.setAppId(5);
			Date problemTime = new Date();
			problem.setProblemTime(problemTime);
			workerDao.insertProblem(problem);
			if (imgs != null) {
				JSONArray jsonimgs = JSONArray.parseArray(imgs);
				for (int a = 0; a < jsonimgs.size(); a++) {
					Map<String, Object> map = new HashMap<>();
					map.put("img", jsonimgs.get(a));
					map.put("problemId", problem.getProblemId());
					workerDao.insertWenti(map);
				}
			}
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询消息中心
	public BuluResult selectMessage(Integer page) {
		page = 10 * (page - 1);
		List<Map<String, Object>> list = merchantsDao.selectMessage(page);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无数据!!!");
		}
		return buluResult;
	}

	// 更改手机号
	public BuluResult updatePhone(HttpServletRequest request, String account) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		BuluResult buluResult = new BuluResult();
		JSONObject object = getAccountMap(account);
		String password = object.getString("password");
		// 验证密码是否正确
		Map<String, Object> mima = merchantsDao.selectPassword(merchantsId);
		String weiyi = (String) mima.get("weiyi");
		password = MD5Utils.MD5(password + weiyi);
		String yuanmima = (String) mima.get("password");
		if (yuanmima.equals(password)) {
			// 修改手机号
			// Map<String, Object> map = new HashMap<>();
			// map.put("merchantsId", merchantsId);
			// map.put("phone", phone);
			// merchantsDao.updatePhone(phone);
			buluResult.setStatus(0);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("密码错误!!!");
		}
		return buluResult;
	}

	// 更换手机号
	public BuluResult replacePhone(HttpServletRequest request, String phone) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 修改手机号
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsId", merchantsId);
		map.put("phone", phone);
		merchantsDao.updatePhone(map);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 添加房间
	public BuluResult insertRoom(Integer indentId, Goods goods) {
		// 把goods存到商品表中并获取id
		//logger.error("点击添加商品的时候就已经调用这个方法，存储之间的关系............................");
		merchantsDao.insertGoods(goods);
		// 把商品号与订单号关联一下
		Map<String, Object> send = new HashMap<>();
		send.put("goodsId", goods.getGoodsId());
		send.put("indentId", indentId);
		merchantsDao.insertindentGoods(send);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 根据商品号查询商品
	public BuluResult selectGoodxinxi(Integer goodsId) {
		Map<String, Object> map = workerDao.selectGoodxinxi(goodsId);
		if ((Integer) map.get("type") == 0) {// 布艺帘
			List<Map<String, Object>> list = workerDao.selectSpecial(goodsId);
			for (int a = 0; a < list.size(); a++) {
				List<String> imgs = workerDao.selectImgs((Integer) list.get(a).get("specialId"));
				list.get(a).put("imgs", imgs);
				// 获得安装位置拍照
				List<String> installImgs = workerDao.selectInstallImgs((Integer) list.get(a).get("specialId"));
				list.get(a).put("installImgs", installImgs);
			}
			map.put("specials", list);
		} else {// 成品帘
			// 根据goodsId查找旗下的所有special参数
			List<Map<String, Object>> list = workerDao.selectFinishSpecial(goodsId);
			for (int a = 0; a < list.size(); a++) {
				// 查找该special下的照片
				List<String> imgs = merchantsDao.selectChengpinImgs((Integer) list.get(a).get("specialId"));
				list.get(a).put("imgs", imgs);
				// 获得安装位置拍照
				List<String> installImgs = workerDao.selectInstallImgs((Integer) list.get(a).get("specialId"));
				list.get(a).put("installImgs", installImgs);
				Goods goods = merchantsDao.selectGoodxinxi((Integer) list.get(a).get("accId"));
				list.get(a).put("pinstallSite", goods.getPinstallSite());
			}
			map.put("specials", list);
			/*
			 * List<String> imgs = workerDao.selectImgsCpl((Integer)
			 * map.get("goodsId")); map.put("measureImgs", imgs); List<String>
			 * installImgs = workerDao.selectImgsCplInstall((Integer)
			 * map.get("goodsId")); map.put("installImgs", installImgs);
			 */
			/*
			 * List<Map<String, Object>> list =
			 * workerDao.selectSpecial(goodsId); for (int a = 0; a <
			 * list.size(); a++) { List<String> imgs =
			 * workerDao.selectImgs((Integer) list.get(a).get("specialId"));
			 * Goods goods = merchantsDao.selectGoodxinxi((Integer)
			 * list.get(a).get("accId")); list.get(a).put("pinstallSite",
			 * goods.getAccessoriesType()); list.get(a).put("imgs", imgs); //
			 * 获得安装位置拍照 List<String> installImgs =
			 * workerDao.selectInstallImgs((Integer)
			 * list.get(a).get("specialId")); list.get(a).put("installImgs",
			 * installImgs); } map.put("specials", list);
			 */
		}
		if (map.get("locationId") != null) {
			String locationContent = workerDao.selectLocationConent((Integer) map.get("locationId"));
			map.put("locationContent", locationContent);
		} else {
			map.put("locationContent", map.get("otherRoom"));
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		//logger.error("==" + JSONObject.toJSONString(map));
		buluResult.setData(map);
		return buluResult;
	}

	// 修改订单地址
	public BuluResult updateIndent(Integer indentId, Customer_address address, String baseAddress, String detailAddress,
			String isNeedTakeGoods, Long subscribeTime,String takeGoodsTel) {
		String city = address.getCity();
		String area = address.getArea();
		// 修改地址
		Map<String, Object> addressMap = merchantsDao.selectIndent(indentId);
		Integer type = (int) addressMap.get("type");//判断订单类型
		Map<String, Object> map = new HashMap<>();
		Double merchantsPrice = 0.0;
		Double indentPrice = 0.0;
		Double workerRealPrice = 0.0;
		Double merchantsRealPrice = 0.0;
		if (type == 0) {//测量单
			if (address.getProvince() == null || address.getCity() == null || address.getArea() == null) {// 如果没有传来安装{维修}地址，认为没修过此项
				city = (String) addressMap.get("city");
				area = (String) addressMap.get("area");
				address.setProvince((String) addressMap.get("province"));
				address.setCity((String) addressMap.get("city"));
				address.setArea((String) addressMap.get("area"));
			}
			
			String areaCode = getCodeByCityAndArea(city, area);
			address.setAreaCode(areaCode);
			merchantsDao.updateAddress(address);
			
			Map<String, Object> mapM = merchantsDao.selectCPriceByCity(city, 1);
			Map<String, Object> mapGR = merchantsDao.selectCPriceByCity(city, 0);
			// //logger.error(roomNumB);selectXiangqing
			// //logger.error(map.get("roomNumber"));

			Integer roomNumB = (Integer) addressMap.get("roomNumB");
			merchantsPrice = meaPrice(mapM, roomNumB, merchantsPrice);
			indentPrice = meaPrice(mapGR, roomNumB, indentPrice);
			map.put("indentId", indentId);
			map.put("merchantsPrice", merchantsPrice);
			map.put("indentPrice", indentPrice);
			map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
			
		}else if(type == 1){//安装单
			if (address.getProvince() == null || address.getCity() == null || address.getArea() == null) {// 如果没有传来安装{维修}地址，认为没修过此项
				city = (String) addressMap.get("city");
				area = (String) addressMap.get("area");
				address.setProvince((String) addressMap.get("province"));
				address.setCity((String) addressMap.get("city"));
				address.setArea((String) addressMap.get("area"));
			} else {
				// 修改地址，重新计价
				// 根据订单号查询所有商品
				List<Goods> list = merchantsDao.selectAllGoods(indentId, 0);

				
				if (list.size() > 0) {
					for (int a = 0; a < list.size(); a++) {
						Map<String, Object> map1 = jisuanAnzhuan(list.get(a), city);
						merchantsPrice = Arith.add(merchantsPrice, (Double) map1.get("merchantsPrice"));
						indentPrice = Arith.add(indentPrice, (Double) map1.get("indentPrice"));
					}
					workerRealPrice = indentPrice;
					merchantsRealPrice = merchantsPrice;
					Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
					Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity(city, 0);

					merchantsPrice = Math.max(merchantsPrice, (Double) merchantsPriceMap.get("installStartingFare"));
					indentPrice = Math.max(indentPrice, (Double) workerPriceMap.get("installStartingFare"));

					// 判断是否需要取货
					Integer isNeedTakeGood = merchantsDao.selectIsNeedTakeGoods(indentId);
					if (isNeedTakeGood != null && isNeedTakeGood == 1) {
						merchantsPrice = Arith.add(merchantsPrice, (double) merchantsPriceMap.get("takeGoodsPrice"));
						indentPrice = Arith.add(indentPrice, (double) workerPriceMap.get("takeGoodsPrice"));
					}
				}

				Map<String, Object> charu = new HashMap<>();
				charu.put("indentId", indentId);
				charu.put("merchantsPrice", merchantsPrice);
				charu.put("indentPrice", indentPrice);
				charu.put("workerRealPrice", workerRealPrice);
				charu.put("merchantsRealPrice", merchantsRealPrice);
				merchantsDao.updateindentPrice(charu);
			}
			String areaCode = getCodeByCityAndArea(city, area);

			address.setAreaCode(areaCode);
			merchantsDao.updateAddress(address);
			// 修改订单地址
			Map<String, Object> price = merchantsDao.selectIndent(indentId);

			if (!(isNeedTakeGoods == null)) {
				// 20是被定死的取货费
				if (Integer.parseInt(isNeedTakeGoods) == 1) {// 证明用户又改成 需要 取货了
					if (price.get("isNeedTakeGoods") == null || 0 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为0或null，存1，加20
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 1表示需要取货
						map.put("indentPrice", Arith.add((Double) price.get("indentPrice"), 20));
						map.put("merchantsPrice", Arith.add((Double) price.get("merchantsPrice"), 20));
					} else if (1 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为1，存1，价格不变
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 1表示需要取货
						map.put("indentPrice", (Double) price.get("indentPrice"));
						map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
					}
				} else if (Integer.parseInt(isNeedTakeGoods) == 0) {// 证明用户又改成 不需要
																	// 取货了
					if (price.get("isNeedTakeGoods") == null || 0 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为0或null，存0，价格不变
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
						map.put("indentPrice", (Double) price.get("indentPrice"));
						map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
					} else if (1 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为1，存0，减20
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
						map.put("indentPrice", Arith.sub((Double) price.get("indentPrice"), 20));
						map.put("merchantsPrice", Arith.sub((Double) price.get("merchantsPrice"), 20));
					}
				}
			} else {
				map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
				map.put("indentPrice", (Double) price.get("indentPrice"));
				map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
			}
			
		}else if (type == 2) {//维修单
			if (address.getProvince() == null || address.getCity() == null || address.getArea() == null) {// 如果没有传来安装{维修}地址，认为没修过此项
				city = (String) addressMap.get("city");
				area = (String) addressMap.get("area");
				address.setProvince((String) addressMap.get("province"));
				address.setCity((String) addressMap.get("city"));
				address.setArea((String) addressMap.get("area"));
			}
			
			String areaCode = getCodeByCityAndArea(city, area);
			address.setAreaCode(areaCode);
			merchantsDao.updateAddress(address);
			
			Map<String, Object> price = merchantsDao.selectIndent(indentId);
			if (!(isNeedTakeGoods == null)) {
				// 20是被定死的取货费
				if (Integer.parseInt(isNeedTakeGoods) == 1) {// 证明用户又改成 需要 取货了
					if (price.get("isNeedTakeGoods") == null || 0 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为0或null，存1，加20
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 1表示需要取货
						map.put("indentPrice", Arith.add((Double) price.get("indentPrice"), 20));
						map.put("merchantsPrice", Arith.add((Double) price.get("merchantsPrice"), 20));
					} else if (1 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为1，存1，价格不变
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 1表示需要取货
						map.put("indentPrice", (Double) price.get("indentPrice"));
						map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
					}
				} else if (Integer.parseInt(isNeedTakeGoods) == 0) {// 证明用户又改成 不需要
																	// 取货了
					if (price.get("isNeedTakeGoods") == null || 0 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为0或null，存0，价格不变
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
						map.put("indentPrice", (Double) price.get("indentPrice"));
						map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
					} else if (1 == ((Long) price.get("isNeedTakeGoods"))) {// 原本为1，存0，减20
						map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
						map.put("indentPrice", Arith.sub((Double) price.get("indentPrice"), 20));
						map.put("merchantsPrice", Arith.sub((Double) price.get("merchantsPrice"), 20));
					}
				}
			} else {
				map.put("isNeedTakeGoods", isNeedTakeGoods);// 0表示不需要取货
				map.put("indentPrice", (Double) price.get("indentPrice"));
				map.put("merchantsPrice", (Double) price.get("merchantsPrice"));
			}
		}
		
		map.put("indentId", indentId);
		map.put("baseAddress", (baseAddress == null || "".equals(baseAddress )) ? "无" : baseAddress);
		map.put("detailAddress", (detailAddress == null || "".equals(detailAddress )) ? "无" : detailAddress);
		map.put("subscribeTime", (subscribeTime == null || "".equals(subscribeTime )) ? subscribeTime : new Date(subscribeTime));
		map.put("takeGoodsTel", (takeGoodsTel == null || "".equals(takeGoodsTel )) ? "无" : takeGoodsTel);
		
		merchantsDao.updateIndentAddress(map);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 从测量日记中生成安装订单
	public BuluResult insertAindent(HttpServletRequest request, Integer indentId, String goodsIds, Long subscribeTime) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 根据订单号查询安装地址
		Map<String, Object> map = merchantsDao.selectCity(indentId);
		Map<String, String> m = new HashMap<>();
		m.put("city", (String) map.get("city"));
		m.put("area", (String) map.get("area"));
		String areaCode = merchantsDao.selectAreaCode(m);
		// 判断测量日记的地址是否为已开通城市
		BuluResult b = theAreaIsDredge((String) map.get("city"), areaCode);
		HashMap m2 = (HashMap) b.getData();
		BuluResult buluResult = new BuluResult();
		Indent indent;
		if ((int) (m2.get("theAreaIsDredge")) == 1) {// 已开通
			indent = new Indent();
			indent.setSubscribeTime(new Date(subscribeTime));
			indent.setCustomerId(merchantsId);
			indent.setCuAdId((Integer) map.get("cuAdId"));
			indent.setBeginTime(new Date());
			indent.setType(1);
			indent.setIndentType(3);
			indent.setBaseAddress((String) map.get("baseAddress"));
			indent.setDetailAddress((String) map.get("detailAddress"));
			indent.setTakeGoodsTel((String) map.get("takeGoodsTel"));
			//indent.setOrderId(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId));
			indent.setRemark((String) map.get("remark"));
			indent.setIsNeedTakeGoods(Integer.parseInt(map.get("isNeedTakeGoods").toString()));
			//复制一份测量日记中的测量订单数据保存在indent表中，标记为安装订单
			merchantsDao.insertAnzhuangIndent(indent);
			Double merchantsPrice = 0.0;
			Double indentPrice = 0.0;
			Double workerRealPrice = 0.0;
			Double merchantsRealPrice = 0.0;
			JSONArray jsonArray = JSONObject.parseArray(goodsIds);
			// 根据订单号查询市
			String city = (String) map.get("city");
			// 获取市
			for (int a = 0; a < jsonArray.size(); a++) {
				// 根据商品号查询商品
				Goods goods = merchantsDao.selectGoodxinxi(jsonArray.getInteger(a));
				Map<String, Object> price = jisuanAnzhuan(goods, city);
				merchantsPrice = Arith.add(merchantsPrice, (Double) price.get("merchantsPrice"));
				indentPrice = Arith.add(indentPrice, (Double) price.get("indentPrice"));

				// 修改商品变为已经下过安装订单
				merchantsDao.updateGoodsInstall(jsonArray.getInteger(a));
				
				/*//复制本次测量到安装需要下单的商品，存放在刚转化的安装订单名下,2017-5-7该方法适用后决定暂时废弃，拷贝数据太多
				Integer id = merchantsDao.copyGoodsByGoodsId(goods);*/
				
				// 把商品和订单的关系加入数据库
				Map<String, Object> send = new HashMap<>();
				send.put("goodsId", goods.getGoodsId());
				send.put("indentId", indent.getIndentId());
				merchantsDao.insertindentGoods(send);
			}

            workerRealPrice = indentPrice;
			merchantsRealPrice = merchantsPrice;
			Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
			Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity(city, 0);

			merchantsPrice = Math.max(merchantsPrice, (Double) merchantsPriceMap.get("installStartingFare"));
			indentPrice = Math.max(indentPrice, (Double) workerPriceMap.get("installStartingFare"));

			// 判断是否需要取货
			Integer isNeedTakeGoods = merchantsDao.selectIsNeedTakeGoods(indentId);
			if (isNeedTakeGoods != null && isNeedTakeGoods == 1) {
				merchantsPrice = Arith.add(merchantsPrice, (double) merchantsPriceMap.get("takeGoodsPrice"));
				indentPrice = Arith.add(indentPrice, (double) workerPriceMap.get("takeGoodsPrice"));
			}

			Map<String, Object> xiugai = new HashMap<>();
			Integer goodsNum = workerDao.selectGoodsNum(indentId);
			xiugai.put("roomNumB", goodsNum==null?0:goodsNum);
			xiugai.put("indentId", indent.getIndentId());
			xiugai.put("merchantsPrice", merchantsPrice);
			xiugai.put("indentPrice", indentPrice);
			xiugai.put("workerRealPrice", workerRealPrice);
			xiugai.put("merchantsRealPrice", merchantsRealPrice);
			// 修改安装订单的价格
			merchantsDao.updateAIndent(xiugai);
			buluResult.setStatus(0);
			buluResult.setData(indent.getIndentId());
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("原谅我不规范一次,该日记城市未开通,不可以下单!");
		}

		return buluResult;
	}

	// 用于计算价格
	private Double[] getPrice(List<Map<String, Object>> list, int position, double merchantsPrice, double indentPrice,
			Map<String, Object> parts, boolean isSingle) {
		Cost_rules anzhuang = merchantsDao.selectAPrice(parts);// 商家价格
		Cost_rules anzhuangGR = merchantsDao.selectAPriceGR(parts);// 工人价格
		// 判断配件米数与基础米数比较,（应该是四种情况，宽度4米内{高度3米内}{高度3米外}，宽度4米外{高度3米内}{高度3米外}）
		double widthBasisMeter = anzhuang.getWidthBasisMeter();// 基础宽
		double width = (Double) list.get(position).get("saleNumber");// 计费宽度
		//logger.error("===计算价格的list===" + JSONObject.toJSONString(list));
		double heightBasisMeter = anzhuang.getHeightBasisMeter();// 基础高
		double height = (Double) list.get(position).get("high");// 计费高度

		if (widthBasisMeter >= width && heightBasisMeter >= height) {// 宽高均在正常范围内,isSingle控制计算单双层价格
			merchantsPrice = Arith.add(merchantsPrice, isSingle ? anzhuang.getSingle() : anzhuang.getDoubleDeck());
			indentPrice = Arith.add(indentPrice, isSingle ? anzhuangGR.getSingle() : anzhuangGR.getDoubleDeck());
		} else if (widthBasisMeter >= width && heightBasisMeter < height) {// 宽正常，高超标
			// 计算商家价格
			merchantsPrice = pricePartOne(anzhuang, height, heightBasisMeter, merchantsPrice, isSingle);

			// 计算工人价格(订单价)
			indentPrice = pricePartOne(anzhuangGR, height, heightBasisMeter, indentPrice, isSingle);

		} else if (widthBasisMeter < width && heightBasisMeter >= height) {// 宽超标，高正常
			// 计算商家价格
			merchantsPrice = pricePartTwo(anzhuang, width, widthBasisMeter, merchantsPrice, isSingle);

			// 计算工人价格(订单价)
			indentPrice = pricePartTwo(anzhuangGR, width, widthBasisMeter, indentPrice, isSingle);
		} else {// 宽超标，高超标
			// 计算商家价格
			merchantsPrice = pricePartThree(anzhuang, width, height, widthBasisMeter, heightBasisMeter, merchantsPrice,
					isSingle);

			// 计算工人价格(订单价)
			indentPrice = pricePartThree(anzhuangGR, width, height, widthBasisMeter, heightBasisMeter, indentPrice,
					isSingle);
		}
		Double[] price = new Double[2];
		price[0] = merchantsPrice;
		price[1] = indentPrice;
		return price;
	}

	// 计算高超标价格
	private double pricePartOne(Cost_rules part, Double height, Double heightBasisMeter, Double price,
			boolean isSingle) {
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reduction = Arith.sub(height, heightBasisMeter);// 高度超标量
		Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, part.getHeightBeyondMeter()))),
				part.getHeightBeyondUnitPrice());
		price = Arith.add(Arith.add(basePrice, chaochu), price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	// 计算宽超标价格
	private double pricePartTwo(Cost_rules part, Double width, Double widthBasisMeter, Double price, boolean isSingle) {
		// 计算商家价格
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reduction = Arith.sub(width, widthBasisMeter);// 宽度超标量
		Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, part.getWidthBeyondMeter()))), basePrice);
		price = Arith.add(Arith.add(basePrice, chaochu), price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	// 计算宽高都超标价格
	private double pricePartThree(Cost_rules part, Double width, Double height, Double widthBasisMeter,
			Double heightBasisMeter, Double price, boolean isSingle) {
		// 计算商家价格
		double basePrice = isSingle ? part.getSingle() : part.getDoubleDeck();// 基础价格，便于宽度或高度超标时累计单价
		Double reductions = Arith.sub(height, heightBasisMeter);// 高度超标量 5
		Double reduction = Arith.sub(width, widthBasisMeter);// 宽度超标量 6
		Double chaochus = Arith.mul((Math.ceil(Arith.div(reductions, part.getHeightBeyondMeter()))),
				part.getHeightBeyondUnitPrice());// 100
		Double heightPrice = Arith.add(basePrice, chaochus);// 120
		Double total = Arith.mul((Math.ceil(Arith.div(reduction, part.getWidthBeyondMeter()))) + 1, heightPrice);// 360
		price = Arith.add(total, price);
		// return Math.max(price, part.getInstallStartingFare());
		return price;
	}

	// 计算一个商品的安装费
	public Map<String, Object> jisuanAnzhuan(Goods goods, String city) {
		Double merchantsPrice = 0.0;
		Double indentPrice = 0.0;
		if (goods.getType() == 0) {// 布艺帘
			if (goods.getStructure() == 0) {// 单布
				// 获取布配件集合(特殊安装有多少个所以要用集合)
				List<Map<String, Object>> list = merchantsDao.selectBupeijian(goods.getGoodsId());

				for (int b = 0; b < list.size(); b++) {
					String panzhuangfangshi = (String) list.get(b).get("panzhuangfangshi");// 配件安装方式
					// 计算布配件安装费
					// 根据配件类型还有地域获得计算方式
					Map<String, Object> bupeijian = new HashMap<>();
					bupeijian.put("type", list.get(b).get("accessoriesType"));
					bupeijian.put("city", city);
					Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
					merchantsPrice = price[0];
					indentPrice = price[1];

					// 判断安装配件只会含有‘装单’或‘双联码’
					if (panzhuangfangshi.indexOf("装单") > 0) {// 含有
																// 若有帘头则为单独安装按单层价格计算
						// 判断是否有帘头
						if (goods.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, true);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					} else {// 不含有‘装单’ 肯定为双联码 肯定有帘头且按双层计算
							// 判断是否有帘头
						if (goods.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}
			} else if (goods.getStructure() == 1) {// 单纱
				// 获取纱配件集合(特殊安装有多少个所以要用集合)
				List<Map<String, Object>> list = merchantsDao.selectShapeijian(goods.getGoodsId());
				for (int b = 0; b < list.size(); b++) {
					String panzhuangfangshi = (String) list.get(b).get("panzhuangfangshi");// 配件安装方式
					// 计算布配件安装费
					// 根据配件类型还有地域获得计算方式
					Map<String, Object> bupeijian = new HashMap<>();
					bupeijian.put("type", list.get(b).get("accessoriesType"));
					bupeijian.put("city", city);
					Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
					merchantsPrice = price[0];
					indentPrice = price[1];

					// 判断安装配件只会含有‘装单’或‘双联码’
					if (panzhuangfangshi.indexOf("装单") > 0) {// 含有
																// 若有帘头则为单独安装按单层价格计算
						// 判断是否有帘头
						if (goods.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 1);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, true);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					} else {// 不含有‘装单’ 肯定为双联码 肯定有帘头且按双层计算
							// 判断是否有帘头
						if (goods.getShadeHead() == 1) {// 帘头按照单层计算
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 1);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}
			} else {// 布+纱
					// 获取布配件集合(特殊安装有多少个所以要用集合)
				List<Map<String, Object>> list = merchantsDao.selectBupeijian(goods.getGoodsId());
				List<Map<String, Object>> shapeijian = merchantsDao.selectShapeijian(goods.getGoodsId());
				if (shapeijian != null && shapeijian.size() > 0) {// 有单独的纱配件说明是布纱单独安装，纱按单层价格计算
					for (int i = 0; i < shapeijian.size(); i++) {
						// 计算纱配件安装费
						// 根据配件类型还有地域获得计算方式
						Map<String, Object> peijiansha = new HashMap<>();
						peijiansha.put("type", shapeijian.get(i).get("accessoriesType"));
						peijiansha.put("city", city);
						Double[] price = getPrice(shapeijian, i, merchantsPrice, indentPrice, peijiansha, true);
						merchantsPrice = price[0];
						indentPrice = price[1];
					}

					// 有纱尺寸时走的逻辑
					for (int b = 0; b < list.size(); b++) {
						String panzhuangfangshi = (String) list.get(b).get("panzhuangfangshi");
						// 判断其中包含的字符串
						if (panzhuangfangshi.indexOf("装单") >= 0) {//
							// 证明全部单独安装,因为没有纱配件，所有按照
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							// 第一次计价，相当于计算单布安装费
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
							merchantsPrice = price[0];//
							indentPrice = price[1];//

							// 计算帘头配件安装费
							// 判断是否有帘头
							if (goods.getShadeHead() == 1) {// 帘头按照单层计算(布纱双层分开，顶装单安装码，布纱帘全独立安装)
								// 获得帘头配件
								int goodsIdChild = goods.getGoodsId() * 10 + b;
								List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
										goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("city", city);
								Double[] price2 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price2[0];
								indentPrice = price2[1];
							}

						} else if (panzhuangfangshi.indexOf("装双") >= 0) {
							// 证明布纱双层安装
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 计算帘头配件安装费
							// 判断是否有帘头
							if (goods.getShadeHead() == 1) {// 帘头按照单层计算
								// 获得帘头配件
								int goodsIdChild = goods.getGoodsId() * 10 + b;
								List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
										goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("city", city);
								Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										false);
								merchantsPrice = price1[0];
								indentPrice = price1[1];
							}
						} else if (panzhuangfangshi.indexOf("双联码") >= 0) {
							// 判断布纱安装位置是否一致
							if (goods.getInstallCase() == 1) {// 布纱安装情况一致 证明没有帘头
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", list.get(b).get("accessoriesType"));
								bupeijian.put("city", city);
								Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, false);
								merchantsPrice = price[0];
								indentPrice = price[1];
							} else {// 布纱安装情况不一致 证明有帘头
									// 证明布+纱单独安装 帘头不单独
									// 计算布配件安装费
									// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", list.get(b).get("accessoriesType"));
								bupeijian.put("city", city);
								Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
								merchantsPrice = price[0];
								indentPrice = price[1];
								// 计算帘头配件安装费
								// 判断是否有帘头
								if (goods.getShadeHead() == 1) {// 帘头按照一体帘头计算
									// 获得帘头配件
									int goodsIdChild = goods.getGoodsId() * 10 + b;
									List<Map<String, Object>> toupeijian = merchantsDao
											.selectToupeijian(goods.getGoodsId(), goodsIdChild, 0);
									Map<String, Object> lianpeijian = new HashMap<>();
									lianpeijian.put("type", "帘头");
									lianpeijian.put("city", city);
									Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
											false);
									merchantsPrice = price1[0];
									indentPrice = price1[1];
								}
							}
						} else {// 三联码 这种情况有吗？
								// 证明布+纱双层安装 帘头不单独
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}

				} else {

					// 没有纱尺寸时走的逻辑
					for (int b = 0; b < list.size(); b++) {
						String panzhuangfangshi = (String) list.get(b).get("panzhuangfangshi");
						// 判断其中包含的字符串
						if (panzhuangfangshi.indexOf("装单") >= 0) {//
							// 证明全部单独安装,因为没有纱配件，所有按照
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);// 第一次计价，相当于计算单布安装费
							merchantsPrice = price[0];//
							indentPrice = price[1];//
							Double[] price1 = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);// 第二次计价，相当于计算单纱安装费
							merchantsPrice = price1[0];//
							indentPrice = price1[1];//

							// 计算帘头配件安装费
							// 判断是否有帘头
							if (goods.getShadeHead() == 1) {// 帘头按照单层计算(布纱双层分开，顶装单安装码，布纱帘全独立安装)
								// 获得帘头配件
								int goodsIdChild = goods.getGoodsId() * 10 + b;
								List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
										goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("city", city);
								Double[] price2 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price2[0];
								indentPrice = price2[1];
							}
						} else if (panzhuangfangshi.indexOf("装双") >= 0) {
							// 证明布纱双层安装
							// 计算布配件安装费
							// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 计算帘头配件安装费
							// 判断是否有帘头
							if (goods.getShadeHead() == 1) {// 帘头按照独立帘头计算
								// 获得帘头配件
								int goodsIdChild = goods.getGoodsId() * 10 + b;
								List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
										goodsIdChild, 0);
								Map<String, Object> lianpeijian = new HashMap<>();
								lianpeijian.put("type", "帘头");
								lianpeijian.put("city", city);
								Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
										true);
								merchantsPrice = price1[0];
								indentPrice = price1[1];
							}
						} else if (panzhuangfangshi.indexOf("双联码") >= 0) {
							// 判断布纱安装位置是否一致
							if (goods.getInstallCase() == 1) {// 布纱安装情况一致 证明没有帘头
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", list.get(b).get("accessoriesType"));
								bupeijian.put("city", city);
								Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, false);
								merchantsPrice = price[0];
								indentPrice = price[1];
							} else {// 布纱安装情况不一致 证明有帘头
									// 证明布+纱单独安装 帘头不单独
									// 计算布配件安装费
									// 根据配件类型还有地域获得计算方式
								Map<String, Object> bupeijian = new HashMap<>();
								bupeijian.put("type", list.get(b).get("accessoriesType"));
								bupeijian.put("city", city);
								Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, true);
								merchantsPrice = price[0];
								indentPrice = price[1];
								// 计算帘头配件安装费
								// 判断是否有帘头
								if (goods.getShadeHead() == 1) {// 帘头按照一体帘头计算
									// 获得帘头配件
									int goodsIdChild = goods.getGoodsId() * 10 + b;
									List<Map<String, Object>> toupeijian = merchantsDao
											.selectToupeijian(goods.getGoodsId(), goodsIdChild, 0);
									Map<String, Object> lianpeijian = new HashMap<>();
									lianpeijian.put("type", "帘头");
									lianpeijian.put("city", city);
									Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian,
											false);
									merchantsPrice = price1[0];
									indentPrice = price1[1];
								}
							}
						} else {// 三联码 这种情况有吗？
								// 证明布+纱双层安装 帘头不单独
								// 计算布配件安装费
								// 根据配件类型还有地域获得计算方式
							Map<String, Object> bupeijian = new HashMap<>();
							bupeijian.put("type", list.get(b).get("accessoriesType"));
							bupeijian.put("city", city);
							Double[] price = getPrice(list, b, merchantsPrice, indentPrice, bupeijian, false);
							merchantsPrice = price[0];
							indentPrice = price[1];
							// 获得帘头配件
							int goodsIdChild = goods.getGoodsId() * 10 + b;
							List<Map<String, Object>> toupeijian = merchantsDao.selectToupeijian(goods.getGoodsId(),
									goodsIdChild, 0);
							Map<String, Object> lianpeijian = new HashMap<>();
							lianpeijian.put("type", "帘头");
							lianpeijian.put("city", city);
							Double[] price1 = getPrice(toupeijian, 0, merchantsPrice, indentPrice, lianpeijian, false);
							merchantsPrice = price1[0];
							indentPrice = price1[1];
						}
					}
				}
			}
		} else {// 成品帘
				// 根据市获取价格
			// 根据goodsId获取所有Goods_special表中goodsId为当前goodsId的数据
			List<Map<String, Object>> list = merchantsDao.selectFinishedCurtains(goods.getGoodsId());
			Map<String, Object> parts = new HashMap<>();
			parts.put("type", "成品帘");
			parts.put("city", city);
			Cost_rules anzhuang = merchantsDao.selectAPrice(parts);// 商家价格
			Cost_rules anzhuangGR = merchantsDao.selectAPriceGR(parts);// 工人价格

			for (Map<String, Object> map : list) {
				// 判断配件米数与基础米数比较,（应该是两种情况，{高度3米内}{高度3米外}）{商家价格计算}
				double heightBasisMeter = anzhuang.getHeightBasisMeter();// 基础高
				double height = (Double) map.get("high");// 计费高度
				double basePrice = anzhuang.getSingle();// 基础价格，便于宽度或高度超标时累计单价
				if (height > heightBasisMeter ) {
					Double reduction = Arith.sub(height, heightBasisMeter);// 高度超标量
					Double chaochu = Arith.mul((Math.ceil(Arith.div(reduction, anzhuang.getHeightBeyondMeter()))),
							anzhuang.getHeightBeyondUnitPrice());
					merchantsPrice = Arith.add(Arith.add(basePrice, chaochu), merchantsPrice);
				}else{
					merchantsPrice = merchantsPrice + basePrice ;
				}
				
//				merchantsPrice = Math.max(merchantsPrice, anzhuang.getInstallStartingFare());

				// 工人收到的订单价格
				double heightBasisMeter1 = anzhuangGR.getHeightBasisMeter();// 基础高
				double height1 = (Double) map.get("high");// 计费高度
				double basePrice1 = anzhuangGR.getSingle();// 基础价格，便于宽度或高度超标时累计单价
				if (height1 > heightBasisMeter1 ) {
					Double reduction1 = Arith.sub(height1, heightBasisMeter1);// 高度超标量
					Double chaochu1 = Arith.mul((Math.ceil(Arith.div(reduction1, anzhuangGR.getHeightBeyondMeter()))),
						anzhuangGR.getHeightBeyondUnitPrice());
					indentPrice = Arith.add(Arith.add(basePrice1, chaochu1), indentPrice);
				}else {
					indentPrice = indentPrice + basePrice1;
				}
				
//				indentPrice = Math.max(indentPrice, anzhuang.getInstallStartingFare());

			}
			// indentPrice = merchantsDao.selectChengpinPriceGR(city);
			// 商家价格
			// merchantsPrice = merchantsDao.selectChengpinPriceSJ(city);
		}
		// 把安装费存到表中
		Map<String, Object> installPrice = new HashMap<>();
		installPrice.put("goodsId", goods.getGoodsId());
		installPrice.put("installPrice", indentPrice);
		merchantsDao.updateGoodsInstallPrice(installPrice);
		Map<String, Object> map = new HashMap<>();
		map.put("merchantsPrice", merchantsPrice);
		map.put("indentPrice", indentPrice);
		return map;
	}

	// 删除商品
	public BuluResult deleteGoods(String goodsIds,Integer indentId) {
		BuluResult buluResult = new BuluResult();
		JSONArray jsonArray = JSONObject.parseArray(goodsIds);
		//查找订单类型0顾客下的单 1测量日记(鹿客帮用) 2后台人员 3商家下单 4其他待定',
		int indentType = merchantsDao.selectIndentType(indentId);
		int goodsId = -1;
		for (int a = 0; a < jsonArray.size(); a++) {
			// 获取goodsId
			goodsId = jsonArray.getInteger(a);
			Goods goods = merchantsDao.selectGoodxinxi(goodsId);
			if(1==goods.getHasInstall()){//说明有测量日记订单转化为安装订单
				if(indentType==1){//说明删除的是测量日记下的商品并且商品已经下为安装单
					//删除和安装订单的关系
					merchantsDao.deleteGoodsAndIndent(goodsId,indentId);
				}else{
					//删除和安装订单的关系
					merchantsDao.deleteGoodsAndIndent(goodsId,indentId);
					//将其变为未转化过
					merchantsDao.updateGoodsHasInstall(goodsId);
				}
			}else{//说明是直接新建的订单下的商品或者是未转化为安装订单的测量日记下的商品
				// 直接删除商品 将商品状态改为删除
				merchantsDao.deleteGoodsId(goodsId);
				// 删除商品和订单的关系
				merchantsDao.deleteGoodsAndIndent(goodsId,indentId);
				/*merchantsDao.deleteGoodsIndent(goodsId);*/
			}
			
			/*// 删除商品 将商品状态改为删除
			merchantsDao.deleteGoodsId(goodsId);
			// 删除商品和订单的关系
			merchantsDao.deleteGoodsIndent(goodsId);*/
		}
		/**
		 * liuchaoya 2017-4-17 根据goodsIds获取该商品的所属订单的indentId，并对该订单进行重新计价
		 * 测量日记不需要计算价格
		 */
		if (goodsId != -1 && indentType !=1 ) {
			/*int indentId = merchantsDao.selectIndentIdByGoodsId(goodsId);*/
			String city = merchantsDao.selectIndentCity(indentId);
			// 根据订单号查询所有商品
			List<Goods> list = merchantsDao.selectAllGoods(indentId, 0);

			Double merchantsPrice = 0.0;
			Double indentPrice = 0.0;
			Double workerRealPrice = 0.0;
			Double merchantsRealPrice = 0.0;
			if(null==list || list.size()==0){
				buluResult.setMessage("该订单下目前没有商品,赶快去给订单添加商品吧...");
			}else if (list.size() > 0) {
				for (int a = 0; a < list.size(); a++) {
					Map<String, Object> map = jisuanAnzhuan(list.get(a), city);
					merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
					indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
				}
                workerRealPrice = indentPrice;
				merchantsRealPrice = merchantsPrice;
				Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
				Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity(city, 0);

				merchantsPrice = Math.max(merchantsPrice, (Double) merchantsPriceMap.get("installStartingFare"));
				indentPrice = Math.max(indentPrice, (Double) workerPriceMap.get("installStartingFare"));

				// 判断是否需要取货
				Integer isNeedTakeGoods = merchantsDao.selectIsNeedTakeGoods(indentId);
				if (isNeedTakeGoods != null && isNeedTakeGoods == 1) {
					merchantsPrice = Arith.add(merchantsPrice, (double) merchantsPriceMap.get("takeGoodsPrice"));
					indentPrice = Arith.add(indentPrice, (double) workerPriceMap.get("takeGoodsPrice"));
				}
			}else{
				buluResult.setMessage("您的订单已经暴走到火星,脱离地球重力范围...");
			}

			
			Map<String, Object> charu = new HashMap<>();
			Integer goodsNum = workerDao.selectGoodsNum(indentId);
			charu.put("goodsNum", goodsNum==null?0:goodsNum-1);
			charu.put("indentId", indentId);
			charu.put("merchantsPrice", merchantsPrice);
			charu.put("indentPrice", indentPrice);
			charu.put("workerRealPrice", workerRealPrice);
			charu.put("merchantsRealPrice", merchantsRealPrice);
			merchantsDao.updateindentPrice(charu);
		}

		
		buluResult.setStatus(0);
		return buluResult;
	}

	// 根据订单id查询信息
	public BuluResult selectIndent(Integer indentId) {
		// 根据订单号查询一些信息
		// 根据订单号查询市
		// 获取市
		String city = merchantsDao.selectIndentCity(indentId);
		Map<String, Object> priceMap = merchantsDao.selectCPriceByCity(city, 1);
		//logger.error("indent_city==" + city);

		Map<String, Object> send = merchantsDao.selectIndent(indentId);
		send.put("realPrice",send.get("merchantsRealPrice"));
		if (send.get("baseAddress") == null) {
			send.put("baseAddress", "");
			send.put("detailAddress", "");
		}
		// 添加返回测量，安装，维修的起步价，便于前端对价格计算结果对比
		send.put("meaStartingFare", (Double) priceMap.get("meaStartingFare"));
		send.put("installStartingFare", (Double) priceMap.get("installStartingFare"));
		send.put("repairStartingFare", (Double) priceMap.get("repairStartingFare"));

		//logger.error(send);
		// 查询每次加价价格
		Double premium = merchantsDao.selectPremium();
		send.put("premium", premium);
		Double relievedPrice = (Double) priceMap.get("relievedPrice");
		send.put("merchantsPrice", (Double) Arith.add(relievedPrice, (Double) send.get("merchantsPrice")));
		send.put("relievedPrice", relievedPrice);
		
		// 根据市获取璧钩单价备注
		Double biGouPrice = (Double) priceMap.get("crampetPrice");
		Map<String, Object> bigouBeizhu = merchantsDao.selectPeifu(6);
		send.put("biGou",
				(String) bigouBeizhu.get("beginString") + biGouPrice + (String) bigouBeizhu.get("overString"));
		send.put("biGouPrice", biGouPrice);
		// 根据市查询四爪钩单价备注
		Double siZhuaGouPrice = (Double) priceMap.get("fourClawPrice");
		Map<String, Object> siZhuaGou = merchantsDao.selectPeifu(7);
		send.put("siZhuaGou",
				(String) siZhuaGou.get("beginString") + siZhuaGouPrice + (String) siZhuaGou.get("overString"));
		send.put("siZhuaGouPrice", siZhuaGouPrice);
		Map<String, Object> peifu = merchantsDao.selectPeifu(1);
		// 根据市获取电机每台单价
		Double dianjiPrice = (Double) priceMap.get("motorPrice");
		send.put("dianji", (String) peifu.get("beginString") + dianjiPrice + (String) peifu.get("overString"));
		Map<String, Object> beizhu = merchantsDao.selectPeifu(2);
		send.put("jiajiabeizhu", beizhu.get("beginString"));
		Map<String, Object> anxinbao = merchantsDao.selectPeifu(3);
		Double doubleValue = (Double) anxinbao.get("money");
		send.put("anxinbao",
				(String) anxinbao.get("beginString") + doubleValue.intValue() + (String) anxinbao.get("overString"));
		send.put("dianjiPrice", dianjiPrice);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 添加银行卡
	public BuluResult insertBankCard(HttpServletRequest request, String boundBank, String bankNumber) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 吧原来默认该为不是默认
		merchantsDao.updateBankCardM(merchantsId);
		Map<String, Object> map = new HashMap<>();
		map.put("boundBank", boundBank);
		map.put("bankNumber", bankNumber);
		map.put("peopleId", merchantsId);
		merchantsDao.insertBankCard(map);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询银行卡
	public BuluResult selectBankCard(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		List<Map<String, Object>> list = merchantsDao.selectBankCard(merchantsId);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无银行卡数据!!!");
		}
		return buluResult;
	}

	// 设为默认
	public BuluResult updateBankCard(HttpServletRequest request, Integer bankCardId) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 把原来默认该为不是默认
		merchantsDao.updateBankCardM(merchantsId);
		// 把这个银行卡id的银行卡设为默认
		merchantsDao.updateBankCard(bankCardId);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 删除银行卡
	public BuluResult deleteBankCard(Integer bankCardId) {
		merchantsDao.deleteBankCard(bankCardId);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询版权信息
	public BuluResult selectCopyright() {
		String copyright = merchantsDao.selectCopyright();
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(copyright);
		return buluResult;
	}

	// 查询说明
	public BuluResult selectAboutMe() {
		String aboutMe = merchantsDao.selectAboutMe();
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(aboutMe);
		return buluResult;
	}

	// 查询软件使用许可协议
	public BuluResult selectVersionIntroduce() {
		String versionIntroduce = merchantsDao.selectVersionIntroduce();
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(versionIntroduce);
		return buluResult;
	}

	// 查询平台服务协议
	public BuluResult selectAgreement() {
		String agreement = merchantsDao.selectAgreement();
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(agreement);
		return buluResult;
	}

	// 进行支付 type 0测量 1安装 2维修 3加价悬赏 4补差价
	public BuluResult payMoney(HttpServletRequest request, Double addPrice, Integer indentId, Integer relievedBao,
			Integer type, Integer motorNum, Integer bigouNum, Integer sizhuagouNum, Double money, Double totalMoney,String differenceIds) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		//logger.error("===========支付宝支付订单=======================");
		BuluResult buluResult = new BuluResult();
		// 根据订单号查询一些订单的信息
		String city = merchantsDao.selectIndentCity(indentId);
		Map<String, Object> merchantsMap = merchantsDao.selectCPriceByCity(city, 1);
		Map<String, Object> workerMap = merchantsDao.selectCPriceByCity(city, 0);
		String orderInfo = "";
		if (type == 0) {// 下测量单付钱
			//logger.error("支付宝支付测量订单");
			// 根据订单号查询一些订单的信息
			Map<String, Object> map = merchantsDao.selectIndent(indentId);
			addPrice = Arith.add(addPrice, ((Double) map.get("addPrice")) == null ? 0 : (Double) map.get("addPrice"));
			Double merchantsPrice = (Double) map.get("merchantsPrice");
			// 修改订单价格
			Map<String, Object> send = new HashMap<>();
			send.put("indentPrice", map.get("indentPrice"));
			send.put("addPrice", addPrice);
			send.put("merchantsPrice", merchantsPrice);
			send.put("indentId", indentId);
			send.put("relievedBao", relievedBao);
			//logger.error(relievedBao + "==========" + addPrice + "=====" + merchantsPrice + "====");
			// 支付宝订单的请求参数的编辑
			send.put("type", 0);
			send.put("relievedPrice", (Double) merchantsMap.get("relievedPrice"));
			send.put("workerRealPrice", (Double) map.get("workerRealPrice"));
			send.put("merchantsRealPrice", (Double) map.get("merchantsRealPrice"));
			//判断支付总额是否和数据库中的总金额相等
			boolean flag = getToPayMoneyFlag(totalMoney,send);
			if(!flag){
				buluResult.setStatus(1);
				buluResult.setMessage("下单总金额与数据库不匹配,请退出支付页面重新支付");
				return buluResult;
			}
			// 将本次支付宝记录插入数据库 2017-5-5  XGh
			Map<String, Object> map2 = merchantsDao.selectMerchantsWallet((Integer)map.get("customerId"));
			//记录本次记录
			/*merchantsId, indentId, 
			  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
			  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
			int result = merchantswalletRecordService.insertMerchantsWalletRecord((Integer)map.get("customerId"), indentId, 
					(Integer)map2.get("type"), merchantsPrice=Arith.add(merchantsPrice, relievedBao==0?0.00:(Double) merchantsMap.get("relievedPrice")),
					addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
					null, null, TypeOfIndent.MEASURE.getIndex(), 0, "测量订单支付宝支付", null,0, PayMethod.ALIPAY.getMethod());
			
			/*int result = walletRecordService.insertWalletRecord((Integer)map.get("customerId"), indentId, (Integer)map2.get("type"),
					merchantsPrice=Arith.add(merchantsPrice, relievedBao==0?0.00:(Double) merchantsMap.get("relievedPrice")), 
					addPrice,null, null, Arith.add(merchantsPrice, addPrice), 0, 0, "测量订单支付宝支付", 0, "支付宝支付");*/
			send.put("walletRecordId", result);
			Map<String,Object> param = new HashMap<>();
			param.put("merchantsWalletRecordId", result);
			MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(param);
			//生成支付宝请求参数
			orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), totalMoney, 0.00, "鹿客帮测量定单",
					"鹿客帮测量定单", JSONObject.toJSONString(send));
		} else if (type == 1) {// 下安装订单
			//logger.error("=======================================支付宝支付安装订单====================================");
			Map<String, Object> send = new HashMap<>();
			// 确定支付选择的四爪钩，壁钩，电机的各自的个数以及各自的价格，以及计算出来的总价
			send = getBeforePayMoneyNewPriceData(indentId, motorNum, bigouNum, sizhuagouNum, city, merchantsMap,
					workerMap);
			// 根据订单号查询一些订单的信息
			Map<String, Object> map = merchantsDao.selectIndent(indentId);
			addPrice = Arith.add(addPrice,(Double) map.get("addPrice")==null?0.00:(Double) map.get("addPrice"));
			send = getRealIndentPriceAndMerchantsPrice(send,map);
			send.put("addPrice", addPrice);
			send.put("indentId", indentId);
			send.put("relievedBao", relievedBao);
			// 支付宝订单的请求参数的编辑
			send.put("type", 1);
			send.put("relievedPrice", (Double) merchantsMap.get("relievedPrice"));
			//判断支付总额是否和数据库中的总金额是否相等
			boolean flag = getToPayMoneyFlag(totalMoney,send);
			if(!flag){
				buluResult.setStatus(1);
				buluResult.setMessage("下单总金额与数据库不匹配,请退出支付页面重新支付");
				return buluResult;
			}
			// 将本次支付宝记录插入数据库 2017-5-5  XGh
			Double merchantsPrice = (Double)send.get("merchantsPrice");
			merchantsPrice=Arith.add(merchantsPrice, relievedBao==0?0.00:(Double) send.get("relievedPrice"));
			Map<String, Object> map2 = merchantsDao.selectMerchantsWallet((Integer)map.get("customerId"));
			//记录本次记录
			/*merchantsId, indentId, 
			  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
			  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
			int walletRecordId = merchantswalletRecordService.insertMerchantsWalletRecord((Integer)map.get("customerId"), indentId, 
					(Integer)map2.get("type"),merchantsPrice,addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
					null, null, TypeOfIndent.INSTALL.getIndex(), 0, "安装订单支付宝支付", null,0, PayMethod.ALIPAY.getMethod());
			
			send.put("walletRecordId", walletRecordId);
			Map<String,Object> param = new HashMap<>();
			param.put("merchantsWalletRecordId", walletRecordId);
			MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(param);
			orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), totalMoney, 0.00, "鹿客帮安装订单",
					"鹿客帮安装订单", JSONObject.toJSONString(send));
			
		} else if (type == 2) {// 维修订单
			//logger.error("=======================================支付宝支付维修订单======================================");
			Map<String, Object> send = new HashMap<>();
			send = getBeforePayMoneyNewPriceData(indentId, motorNum, bigouNum, sizhuagouNum, city, merchantsMap,
					workerMap);
			// 根据订单号查询一些订单的信息
			Map<String, Object> map = merchantsDao.selectIndent(indentId);
			addPrice = Arith.add(addPrice, (Double) map.get("addPrice")==null?0.00:(Double) map.get("addPrice"));
			Double indentPrice = (Double) map.get("indentPrice");
			Double merchantsPrice = (Double) map.get("merchantsPrice");
			indentPrice = Arith.add(indentPrice, (Double) send.get("indentPrice"));
			merchantsPrice = Arith.add(merchantsPrice, (Double) send.get("merchantsPrice"));
			// 修改订单价格
			send.put("workerRealPrice", Arith.add((Double) map.get("workerRealPrice"), (Double) send.get("indentPrice")));
			send.put("merchantsRealPrice", Arith.add((Double) map.get("merchantsRealPrice"), (Double) send.get("merchantsPrice")));
			send.put("indentPrice", indentPrice);
			send.put("addPrice", addPrice);
			send.put("merchantsPrice", merchantsPrice);
			send.put("indentId", indentId);
			send.put("relievedBao", relievedBao);
			send.put("type", 2);
			send.put("relievedPrice", (Double) merchantsMap.get("relievedPrice"));
			//判断支付总额是否和数据库中的总金额是否相等
			boolean flag = getToPayMoneyFlag(totalMoney,send);
			if(!flag){
				buluResult.setStatus(1);
				buluResult.setMessage("下单总金额与数据库不匹配,请退出支付页面重新支付");
				return buluResult;
			}
			// 将本次支付宝记录插入数据库 	2017-5-5  XGh
			Map<String, Object> map2 = merchantsDao.selectMerchantsWallet((Integer)map.get("customerId"));
			//记录本次记录
			/*merchantsId, indentId, 
			  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
			  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
			int walletRecordId = merchantswalletRecordService.insertMerchantsWalletRecord((Integer)map.get("customerId"), indentId, 
					(Integer)map2.get("type"),merchantsPrice=Arith.add(merchantsPrice, relievedBao==0?0.00:(Double) merchantsMap.get("relievedPrice")),
					addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
					null, null, TypeOfIndent.REPAIR.getIndex(), 0, "维修订单支付宝支付",null, 0, PayMethod.ALIPAY.getMethod());
			
			send.put("walletRecordId", walletRecordId);
			Map<String,Object> param = new HashMap<>();
			param.put("merchantsWalletRecordId", walletRecordId);
			MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(param);
			orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), totalMoney, 0.00, "鹿客帮维修订单",
					"鹿客帮维修订单", JSONObject.toJSONString(send));
		} else if (type == 3) {// 加价悬赏 3加价悬赏没有安心宝(或者之前有) 5有安心宝需付安心宝的钱
			//logger.error("=======================================支付宝进行加价悬赏=========================================");
			// 根据订单号查询一些订单的信息
			Map<String, Object> map = merchantsDao.selectIndent(indentId);
			// 查询安心宝价格
			Map<String, Object> send = new HashMap<>();
			send.put("type", 3);
			send.put("addPrice", addPrice);
			send.put("indentId",indentId);
			send.put("relievedPrice", (Double) merchantsMap.get("relievedPrice"));
			int relievedBaoY  = (Integer)map.get("relievedBao");
			if(relievedBaoY==0){//之前没有选
				send.put("relievedBao", relievedBao);
				//判断支付总额是否和数据库中的总金额是否相等
				boolean flag = getToPayMoneyFlag(totalMoney,send);
				if(!flag){
					buluResult.setStatus(1);
					buluResult.setMessage("下单总金额与数据库不匹配,请退出支付页面重新支付");
					return buluResult;
				}
				/*merchantsId, indentId, 
				  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
				  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
				Double relievedPrice = (relievedBao==0?0.00:(Double) merchantsMap.get("relievedPrice"));
				// 将本次支付宝记录插入数据库 2017-5-5  XGh
				Map<String, Object> map2 = merchantsDao.selectMerchantsWallet((Integer)map.get("customerId"));
				int walletRecordId =merchantswalletRecordService.insertMerchantsWalletRecord((Integer)map.get("customerId"), indentId, 
						(Integer)map2.get("type"), relievedPrice, addPrice, null, null,  Arith.add(relievedPrice,addPrice), 
						null, null, TypeOfIndent.ADD_PRICE.getIndex(), 0, "订单加价悬赏支付宝支付",null, 0, PayMethod.ALIPAY.getMethod());
				map2.put("merchantsWalletRecordId", walletRecordId);
				MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(map2);
				send.put("walletRecordId", walletRecordId);
				orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), totalMoney,0.00 ,
						"鹿客帮订单悬赏加价","鹿客帮订单悬赏加价",  JSONObject.toJSONString(send));
			}else{
				send.put("relievedBao", 0);
				//判断支付总额是否和数据库中的总金额是否相等
				boolean flag = getToPayMoneyFlag(totalMoney,send);
				if(!flag){
					buluResult.setStatus(1);
					buluResult.setMessage("下单总金额与数据库不匹配,请退出支付页面重新支付");
					return buluResult;
				}
				/*merchantsId, indentId, 
				  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
				  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
				// 将本次支付宝记录插入数据库 2017-5-5  XGh
				Map<String, Object> map2 = merchantsDao.selectMerchantsWallet((Integer)map.get("customerId"));
				int walletRecordId =merchantswalletRecordService.insertMerchantsWalletRecord((Integer)map.get("customerId"), indentId, 
						(Integer)map2.get("type"), 0.00, addPrice, null, null,addPrice, 
						null, null, TypeOfIndent.ADD_PRICE.getIndex(), 0, "订单加价悬赏支付宝支付",null, 0, PayMethod.ALIPAY.getMethod());
				map2.put("merchantsWalletRecordId", walletRecordId);
				send.put("relievedBao", relievedBao);
				MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(map2);
				send.put("walletRecordId", walletRecordId);
				orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), totalMoney,0.00 ,
						"鹿客帮订单悬赏加价","鹿客帮订单悬赏加价",  JSONObject.toJSONString(send));
			}
		} else if(type==4){//支付宝补差价
			//获取进行补差价的所有merchantsWalletRecordId
			JSONArray idArray= JSONObject.parseArray(differenceIds);
			//找出本次需要进行补差价的记录differenceId indentId differencePrice cause ispay
			List<Map<String,Object>> differenceList = merchantsDao.selectDifferences(merchantsId,idArray);
			//判断总价是否和传来的总金额是否一样
			boolean flag = getToatalMoneyIsFlag(differenceList,totalMoney);
			if(!flag){
				buluResult.setStatus(1);
				buluResult.setMessage("差价总金额有误,请核对差价总金额");
				return buluResult;
			}
			//封装给回传参数
			Map<String,Object> send = new HashMap<>();
			send.put("differenceIds", differenceIds);//差价的id数组
			send.put("type", 4);//支付宝支付类型
			send.put("merchantsId", merchantsId);//商家或者个人id
			//差价支付宝支付时新建商家订单号
			send.put("orderNo", LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId,PayMethod.ALIPAY.getIndex(),TypeOfIndent.PRICE_DIFFERENCE.getIndex()));
			//生成支付宝参数返回数据
			orderInfo = AlipayParams.getAlipayParams((String)send.get("orderNo"), totalMoney,0.00 ,
					"鹿客帮补差价","鹿客帮补差价",  JSONObject.toJSONString(send));
		}else {// 向钱包充钱
			String timeString = UtilDate.getOrderNum();
			String random = UtilDate.getThree();
			String orderId = String.valueOf(type) + merchantsId + "s" + timeString + random;
			orderInfo = OrderUtil.getOrderInfo("充值钱包-" + orderId, "", String.valueOf(money), orderId,
					Constant.NOTIFY_URL);
		}
		
		buluResult.setStatus(0);
		buluResult.setData(orderInfo);
		return buluResult;
	}
	/**
	 * 支付前核对下单总金额是否一致
	 * @param totalMoney
	 * @param send
	 * @return
	 */
	private boolean getToPayMoneyFlag(Double totalMoney, Map<String, Object> send) {
		int type = (Integer)send.get("type");
		//获取悬赏加价
		Double addPrice=(Double) send.get("addPrice");
		//获取安心宝标志
		int relievedBao=(Integer) send.get("relievedBao");
		//获取安心宝价钱
		Double relievedPrice=(Double) send.get("relievedPrice");
		if(type==0 || type==1 || type==2){//判断测量，安装，维修
			//获取商家应付merchantsPrice
			Double merchantsPrice=(Double) send.get("merchantsPrice");
			Double totalToPay=Arith.add(merchantsPrice, addPrice==null?0.00:addPrice);
			totalToPay = Arith.add(totalToPay, relievedBao==0?0.00:relievedPrice);
			if(totalToPay.compareTo(totalMoney)!=0){
				return false;
			}
		}else if(type == 3){
			Double totalToPay=Arith.add(addPrice, relievedBao==0?0.00:relievedPrice);
			if(totalToPay.compareTo(totalMoney)!=0){
				return false;
			}
		}else{
			return false;
		}
		
		return true;
	}
	/**
	 * 支付前再次比较真实价格和起步价之间的大小
	 * @param send
	 * @param map
	 * @return
	 */
	private Map<String, Object> getRealIndentPriceAndMerchantsPrice(Map<String, Object> send, Map<String, Object> map) {
		//获取在支付之前保存的订单价格indentPrice和商家需要付款的金额merchantsPrice
		Double merchantsPrice = (Double) map.get("merchantsPrice");
		Double indentPrice = (Double) map.get("indentPrice");
		Double parsPrice = (Double) send.get("indentPrice");
		//获取未支付真实价格
		Double workerRealPrice = (Double)map.get("workerRealPrice");
		Double merchantsRealPrice = (Double)map.get("merchantsRealPrice");
		//真实价格加上现在支付页面选择的机器价格(计算支付时的真实价格)
		Double tempWorkerAllPrice = Arith.add(workerRealPrice,(Double) send.get("indentPrice"));
		Double tempAllPrice = Arith.add(merchantsRealPrice,(Double) send.get("merchantsPrice"));
		//获取起步价
		Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity((String)map.get("city"), 1);
		Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity((String)map.get("city"), 0);
		Double merchantsInstallStartingFare = (Double) merchantsPriceMap.get("installStartingFare");
		Double workerInstallStartingFare = (Double) workerPriceMap.get("installStartingFare");

		//比较realPrice 和 merchansPrice 如果相同，认为已超起步价，indentPrice等于原indentPrice加上配件价
		indentPrice = Math.max(workerInstallStartingFare, tempWorkerAllPrice);
		//比较merchantsPrice
		merchantsPrice = Math.max(merchantsInstallStartingFare, tempAllPrice);
//		if(tempAllPrice.compareTo(merchantsInstallStartingFare)>0 && merchantsRealPrice.compareTo(merchantsInstallStartingFare)<0){
//			merchantsPrice = Arith.sub(merchantsPrice, merchantsInstallStartingFare);
//			merchantsPrice = Arith.add(merchantsPrice, tempAllPrice);
//		}else{
//			merchantsPrice = Arith.add(merchantsPrice, (Double) send.get("merchantsPrice"));
//		}

//		if(tempAllPrice.compareTo(workerInstallStartingFare)>0  && merchantsRealPrice.compareTo(merchantsInstallStartingFare)<0){
//			indentPrice = Arith.sub(indentPrice, workerInstallStartingFare);
//			indentPrice = Arith.add(indentPrice, tempAllPrice);
//		}else{
//			indentPrice = Arith.add(indentPrice, (Double) send.get("indentPrice"));
//		}
		//保存计算后的各个价格
		send.put("indentPrice", indentPrice);
		send.put("merchantsPrice", merchantsPrice);
		send.put("workerRealPrice", tempWorkerAllPrice);
		send.put("merchantsRealPrice", tempAllPrice);
		return send;
	}

	/**
	 * 支付宝 安装订单 计算选择的四爪钩，鹰钩，电机的价格
	 * @param indentId
	 * @param motorNum
	 * @param bigouNum
	 * @param sizhuagouNum
	 * @param city
	 * @param merchantsPriceMap
	 * @param workerPriceMap
	 * @return
	 */
	private Map<String, Object> getBeforePayMoneyNewPriceData(Integer indentId, Integer motorNum, Integer bigouNum,
			Integer sizhuagouNum, String city, Map<String, Object> merchantsPriceMap,
			Map<String, Object> workerPriceMap) {
		// 计算选择的四爪钩，鹰钩，电机的价格
		Double merchantsPrice = 0.0;
		Double indentPrice = 0.0;
		// 根据市获取电机每台单价 根据电机数量计算多少钱
		Double dianjiPrice = (Double) merchantsPriceMap.get("motorPrice");
		Double dianjiPriceGR = (Double) workerPriceMap.get("motorPrice");
		merchantsPrice = Arith.add(merchantsPrice, Arith.mul(motorNum, dianjiPrice));
		indentPrice = Arith.add(indentPrice, Arith.mul(motorNum, dianjiPriceGR));
		// 根据璧钩数量计算璧钩价格
		Double bigouPrice = (Double) merchantsPriceMap.get("crampetPrice");
		Double bigouPriceGR = (Double) workerPriceMap.get("crampetPrice");
		merchantsPrice = Arith.add(merchantsPrice, Arith.mul(bigouNum, bigouPrice));
		indentPrice = Arith.add(indentPrice, Arith.mul(bigouNum, bigouPriceGR));
		// 根据四爪钩数量计算四爪钩价格
		Double sizhuagouPrice = (Double) merchantsPriceMap.get("fourClawPrice");
		Double sizhuagouPriceGR = (Double) workerPriceMap.get("fourClawPrice");
		merchantsPrice = Arith.add(merchantsPrice, Arith.mul(sizhuagouNum, sizhuagouPrice));
		indentPrice = Arith.add(indentPrice, Arith.mul(sizhuagouNum, sizhuagouPriceGR));
		// 保存计算的价格以及各自的单价
		Map<String, Object> send2 = new HashMap<>();
		send2.put("indentPrice", indentPrice);
		send2.put("merchantsPrice", merchantsPrice);
		send2.put("motorNum", motorNum);
		send2.put("bigouNum", bigouNum);
		send2.put("sizhuagouNum", sizhuagouNum);
		return send2;
	}

	// 支付订单成功之后回调
	@SuppressWarnings("rawtypes")
	public BuluResult getAlipayapi(HttpServletRequest request) {
		BuluResult buluResult = new BuluResult();
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();

		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		// 商户订单号
		String out_trade_no = "";
		// 支付宝交易号
		// String trade_no = "";
		// 交易状态
		String trade_status = "";
		// 异步通知ID
		String notify_id = "";

		String total_fee = "";

		// sign
		String sign = "";
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		try {
			// 商户订单号
			out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

			// 支付宝交易号
			// trade_no = new
			// String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-7");

			// 交易状态
			trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

			// 交易金额
			total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");

			// 异步通知ID
			notify_id = request.getParameter("notify_id");

			// sign
			sign = request.getParameter("sign");
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (notify_id != "" && notify_id != null) {
			if (AlipayNotify.verifyResponse(notify_id).equals("true")) {// 判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
				if (AlipayNotify.getSignVeryfy(params, sign)) {// 使用支付宝公钥验签
					if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
						// 业务处理
						// 截取字符串得到是什么类型
						Integer type = Integer.parseInt(out_trade_no.substring(0, 1));
						// 截取字符串 类型后面 s前面的值
						Integer nameId = Integer.parseInt(out_trade_no.substring(1, out_trade_no.indexOf("s")));
						if (type == 0 || type == 1 || type == 2) {// 状态为下单支付
																	// 只需要把订单状态改为已付款
							merchantsDao.updateIndentStatusYes(nameId);
							// 根据订单号获取订单信息
							Map<String, Object> map = merchantsDao.selectIndent(nameId);
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date date = new Date();
							try {
								date = simpleDateFormat.parse(map.get("subscribeTime").toString());
							} catch (ParseException e) {
								e.printStackTrace();
							}
							long timeStemp = date.getTime();
							Map<String, String> send = new HashMap<>();
							send.put("subscribeTime", String.valueOf(timeStemp));
							send.put("msgType", "0");
							send.put("status", map.get("status").toString());
							send.put("city", map.get("city").toString());
							send.put("name", map.get("name").toString());
							send.put("indentId", map.get("indentId").toString());
							send.put("cuAdId", map.get("cuAdId").toString());
							send.put("addPrice", map.get("addPrice").toString());
							send.put("phone", map.get("phone").toString());
							send.put("beginTime", map.get("beginTime").toString());
							send.put("address", map.get("address").toString());
							send.put("type", map.get("type").toString());
							if (map.get("baseAddress") != null) {
								send.put("baseAddress", "");
								send.put("detailAddress", "");
							} else {
								send.put("baseAddress", (String) map.get("baseAddress"));
								send.put("detailAddress", (String) map.get("detailAddress"));
							}
							if (map.get("weiXbody") != null) {
								send.put("weiXbody", map.get("weiXbody").toString());
							}
							send.put("merchantsPrice", map.get("merchantsPrice").toString());
							if (map.get("roomNumB") != null) {
								send.put("roomNumB", map.get("roomNumB").toString());
							}
							send.put("remark", map.get("remark").toString());
							send.put("indentPrice", String
									.valueOf(Arith.add((Double) map.get("indentPrice"), (Double) map.get("addPrice"))));
							if (type == 1) {
								Integer number = merchantsDao.selectGoodsNum(nameId);
								send.put("number", String.valueOf(number));
							}
							// 进行推送 0推送订单 1推送消息
							// String timeString = UtilDate.getThree();
							// 根据订单号查询订单信息
							Map<String, Object> indentMap = merchantsDao.selectIndent(nameId);
							Jiguang.JpushIndent(indentMap);
							// JPushClientExample.testSend(map.get("indentId").toString()+timeString,
							// "新订单", "有新订单来了,快来抢单!","0", map);
						} else if (type == 3) {// 为加价悬赏 不包括安心宝价钱
							// 把加的钱添加到订单 再次推送
							Map<String, Object> map = merchantsDao.selectIndent(nameId);
							Double addPrice = (Double) map.get("addPrice");
							addPrice = Arith.add(addPrice, Double.parseDouble(total_fee));
							// 修改订单加价钱数
							Map<String, Object> send2 = new HashMap<>();
							send2.put("indentId", nameId);
							send2.put("addPrice", addPrice);
							merchantsDao.updateAddPrice(send2);
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date date = new Date();
							try {
								date = simpleDateFormat.parse(map.get("subscribeTime").toString());
							} catch (ParseException e) {
								e.printStackTrace();
							}
							long timeStemp = date.getTime();
							Map<String, String> send = new HashMap<>();
							send.put("subscribeTime", String.valueOf(timeStemp));
							send.put("msgType", "0");
							send.put("status", map.get("status").toString());
							send.put("city", map.get("city").toString());
							send.put("name", map.get("name").toString());
							send.put("indentId", map.get("indentId").toString());
							send.put("cuAdId", map.get("cuAdId").toString());
							send.put("addPrice", map.get("addPrice").toString());
							send.put("phone", map.get("phone").toString());
							send.put("beginTime", map.get("beginTime").toString());
							send.put("address", map.get("address").toString());
							send.put("type", map.get("type").toString());
							if (map.get("weiXbody") != null) {
								send.put("weiXbody", map.get("weiXbody").toString());
							}
							send.put("merchantsPrice", map.get("merchantsPrice").toString());
							if (map.get("roomNumB") != null) {
								send.put("roomNumB", map.get("roomNumB").toString());
							}
							if (map.get("baseAddress") != null) {
								send.put("baseAddress", "");
								send.put("detailAddress", "");
							} else {
								send.put("baseAddress", (String) map.get("baseAddress"));
								send.put("detailAddress", (String) map.get("detailAddress"));
							}
							send.put("remark", map.get("remark").toString());
							send.put("indentPrice",
									String.valueOf(Arith.add((Double) map.get("indentPrice"), addPrice)));
							if (type == 1) {
								Integer number = merchantsDao.selectGoodsNum(nameId);
								send.put("number", String.valueOf(number));
							}
							// 进行推送 0推送订单 1推送消息
							// 根据订单号查询订单信息
							Map<String, Object> indentMap = merchantsDao.selectIndent(nameId);
							Jiguang.JpushIndent(indentMap);
							// String timeString = UtilDate.getThree();
							// JPushClientExample.testSend(map.get("indentId").toString()+timeString,
							// "订单悬赏", "该订单已被加价悬赏,快来抢单!","0", map);
						} else if (type == 5) {// 加价悬赏 包括安心宝的价钱
							// 把加的钱添加到订单 再次推送
							Map<String, Object> map = merchantsDao.selectIndent(nameId);

							// 查询安心宝价格
							Double relievedPrice = merchantsDao.selectAnxinbao((String) map.get("city"));

							Double merchantsPrice = Arith.add((Double) map.get("merchantsPrice"), relievedPrice);
							Double addPrice = (Double) map.get("addPrice");
							addPrice = Arith.add(addPrice, Arith.sub(Double.parseDouble(total_fee), relievedPrice));
							// 修改订单加价钱数
							Map<String, Object> send2 = new HashMap<>();
							send2.put("indentId", nameId);
							send2.put("addPrice", addPrice);
							send2.put("relievedBao", 1);
							send2.put("merchantsPrice", merchantsPrice);
							merchantsDao.updateAddPrice2(send2);
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date date = new Date();
							try {
								date = simpleDateFormat.parse(map.get("subscribeTime").toString());
							} catch (ParseException e) {
								e.printStackTrace();
							}
							long timeStemp = date.getTime();
							Map<String, String> send = new HashMap<>();
							send.put("subscribeTime", String.valueOf(timeStemp));
							send.put("msgType", "0");
							send.put("status", map.get("status").toString());
							send.put("city", map.get("city").toString());
							send.put("name", map.get("name").toString());
							send.put("indentId", map.get("indentId").toString());
							send.put("cuAdId", map.get("cuAdId").toString());
							send.put("addPrice", map.get("addPrice").toString());
							send.put("phone", map.get("phone").toString());
							send.put("beginTime", map.get("beginTime").toString());
							send.put("address", map.get("address").toString());
							send.put("type", map.get("type").toString());
							if (map.get("weiXbody") != null) {
								send.put("weiXbody", map.get("weiXbody").toString());
							}
							send.put("merchantsPrice", map.get("merchantsPrice").toString());
							if (map.get("roomNumB") != null) {
								send.put("roomNumB", map.get("roomNumB").toString());
							}
							if (map.get("baseAddress") != null) {
								send.put("baseAddress", "");
								send.put("detailAddress", "");
							} else {
								send.put("baseAddress", (String) map.get("baseAddress"));
								send.put("detailAddress", (String) map.get("detailAddress"));
							}
							send.put("remark", map.get("remark").toString());
							send.put("indentPrice",
									String.valueOf(Arith.add((Double) map.get("indentPrice"), addPrice)));
							if (type == 1) {
								Integer number = merchantsDao.selectGoodsNum(nameId);
								send.put("number", String.valueOf(number));
							}
							// 进行推送 0推送订单 1推送消息
							// 根据订单号查询订单信息
							Map<String, Object> indentMap = merchantsDao.selectIndent(nameId);
							Jiguang.JpushIndent(indentMap);
							// String timeString = UtilDate.getThree();
							// JPushClientExample.testSend(map.get("indentId").toString()+timeString,
							// "订单悬赏", "该订单已被加价悬赏,快来抢单!","0", map);
						} else {// 这个为向钱包充值
								// 根据id查询钱包
							Map<String, Object> wallt = merchantsDao.selectWallet(nameId);
							Double wallet = Arith.add((Double) wallt.get("wallet"), Double.parseDouble(total_fee));
							// 修改钱包金额
							Map<String, Object> send = new HashMap<>();
							send.put("merchantsId", nameId);
							send.put("wallet", wallet);
							merchantsDao.updateWalletD(send);
						}
					}
					buluResult.setStatus(0);
					buluResult.setMessage("成功");
				} else {// 验证签名失败
					buluResult.setStatus(1);
					buluResult.setMessage("验证签名失败!!!");
				}
			} else {// 验证是否来自支付宝的通知失败
				buluResult.setStatus(2);
				buluResult.setMessage("验证是否来自支付宝的通知失败!!!");
			}
		} else {
			buluResult.setStatus(3);
			buluResult.setMessage("未接收到支付宝的通知!!!");
		}
		return buluResult;
	}

	// 生成环信账号
	public BuluResult generateAccount(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 生成一个账号
		String account = "worker" + String.valueOf(merchantsId);
		// 密码
		String password = "123456";
		Map<String, Object> map = new HashMap<>();
		map.put("account", account);
		map.put("password", password);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(map);
		return buluResult;
	}

	// 余额支付 验证密码type 为0测量订单 1安装 2维修 3加价悬赏 4为补差价
	@Transactional
	public BuluResult payBalance(HttpServletRequest request, Double addPrice, Integer indentId, Integer relievedBao,
			Integer type, Integer motorNum, String account, Integer bigouNum, Integer sizhuagouNum,Double totalMoney,String differenceIds) {
		//logger.error("=======================================余额支付开始=========================================");
		BuluResult buluResult = new BuluResult();
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		Map<String, Object> map2 = merchantsDao.selectMerchantsWallet(merchantsId);
		JSONObject object = getAccountMap(account);
		String password = object.getString("password");
		password = MD5Utils.MD5(password + map2.get("weiyi"));
		//logger.error(password);
		//判断余额是否能够支付本次总价
		if(totalMoney.compareTo((Double)map2.get("wallet"))>0){
			buluResult.setStatus(1);
			buluResult.setMessage("余额不足以支付本次业务费用,请更换支付方式或者前去充值");
			return buluResult;
		}
		String city = merchantsDao.selectIndentCity(indentId);
		Map<String, Object> merchantsPriceMap = merchantsDao.selectCPriceByCity(city, 1);
		Map<String, Object> workerPriceMap = merchantsDao.selectCPriceByCity(city, 0);
		if (password.equals(map2.get("password"))) {// 密码正确
			if (type == 0) {// 下测量单付钱
				logger.error("=======================================余额支付测量=========================================");
				// 根据订单号查询一些订单的信息,一些费用也是从数据库中取出来的
				Map<String, Object> map = merchantsDao.selectIndent(indentId);
				addPrice = Arith.add(addPrice, (Double) map.get("addPrice"));
				Double merchantsPrice = (Double) map.get("merchantsPrice");
				/*if (relievedBao == 0) {
					// 查询安心宝价格
					Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");
					merchantsPrice = Arith.sub(merchantsPrice, relievedPrice);
				}*/
				if(relievedBao == 1){
					// 查询安心宝价格
					Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");
					merchantsPrice = Arith.add(merchantsPrice, relievedPrice);
				}
				// 修改订单价格
				Map<String, Object> send2 = new HashMap<>();
				send2.put("addPrice", addPrice);
				send2.put("merchantsPrice", merchantsPrice);
				send2.put("indentId", indentId);
				send2.put("indentPrice", map.get("indentPrice"));
				send2.put("relievedBao", relievedBao);
				send2.put("relievedBao", relievedBao);
				send2.put("workerRealPrice", map.get("workerRealPrice"));
				send2.put("merchantsRealPrice", map.get("merchantsRealPrice"));
				merchantsDao.updateIndent(send2);
				Double wallet = Arith.sub((Double) map2.get("wallet"), Arith.add(merchantsPrice, addPrice));
				Map<String, Object> wat = new HashMap<>();
				wat.put("wallet", wallet);
				wat.put("merchantsId", merchantsId);
				int result = merchantsDao.updateWalletD(wat);
				merchantsDao.updateIndentStatusYes(indentId);
				//记录本次记录
				if(result>0){
					/*merchantsId, indentId, 
					  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
					  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
					merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
							(Integer)map2.get("type"), merchantsPrice, addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
							null, null, TypeOfIndent.MEASURE.getIndex(), 1, "测量订单余额支付",null, 0, PayMethod.BALABCEPAY.getMethod());
					
				}
				// 根据订单号查询订单信息
				Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
				Jiguang.JpushIndent(indentMap);// 通过极光推送订单
			} else if (type == 1) {// 下安装订单
				logger.error("=======================================余额支付安装订单=================================");
				// 重新计价
				// 根据订单号查询所有商品
				List<Goods> list = merchantsDao.selectAllGoods(indentId, 0);
				Double merchantsPrice = 0.0;
				Double indentPrice = 0.0;
				Double workerRealPrice=0.00;
				Double merchantsRealPrice=0.00;
				if (list.size() > 0) {
					for (int a = 0; a < list.size(); a++) {
						Map<String, Object> map = jisuanAnzhuan(list.get(a), city);
						merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
						indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
					}
					// 根据市获取电机每台单价 根据电机数量计算多少钱
					Double dianjiPrice = (Double) merchantsPriceMap.get("motorPrice");
					Double dianjiPriceGR = (Double) workerPriceMap.get("motorPrice");
					merchantsPrice = Arith.add(merchantsPrice, Arith.mul(motorNum, dianjiPrice));
					indentPrice = Arith.add(indentPrice, Arith.mul(motorNum, dianjiPriceGR));
					// 根据璧钩数量计算璧钩价格
					Double bigouPrice = (Double) merchantsPriceMap.get("crampetPrice");
					Double bigouPriceGR = (Double) workerPriceMap.get("crampetPrice");
					merchantsPrice = Arith.add(merchantsPrice, Arith.mul(bigouNum, bigouPrice));
					indentPrice = Arith.add(indentPrice, Arith.mul(bigouNum, bigouPriceGR));
					// 根据四爪钩数量计算四爪钩价格
					Double sizhuagouPrice = (Double) merchantsPriceMap.get("fourClawPrice");
					Double sizhuagouPriceGR = (Double) workerPriceMap.get("fourClawPrice");
					merchantsPrice = Arith.add(merchantsPrice, Arith.mul(sizhuagouNum, sizhuagouPrice));
					indentPrice = Arith.add(indentPrice, Arith.mul(sizhuagouNum, sizhuagouPriceGR));
                    workerRealPrice = indentPrice;
					merchantsRealPrice = merchantsPrice;
					merchantsPrice = Math.max(merchantsPrice, (Double) merchantsPriceMap.get("installStartingFare"));
					indentPrice = Math.max(indentPrice, (Double) workerPriceMap.get("installStartingFare"));

					// 判断是否需要取货
					Integer isNeedTakeGoods = merchantsDao.selectIsNeedTakeGoods(indentId);
					if (isNeedTakeGoods != null && isNeedTakeGoods == 1) {
						merchantsPrice = Arith.add(merchantsPrice, (double) merchantsPriceMap.get("takeGoodsPrice"));
						indentPrice = Arith.add(indentPrice, (double) workerPriceMap.get("takeGoodsPrice"));
					}
				}
				if (relievedBao == 1) {
					// 查询安心宝价格
					Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");
					merchantsPrice = Arith.add(merchantsPrice, relievedPrice);
				}
				
				// 修改订单价格
				Map<String, Object> send2 = new HashMap<>();
				send2.put("indentPrice", indentPrice);
				send2.put("workerRealPrice", workerRealPrice);
				send2.put("merchantsRealPrice", merchantsRealPrice);
				send2.put("motorNum", motorNum);
				send2.put("bigouNum", bigouNum);
				send2.put("sizhuagouNum", sizhuagouNum);
				send2.put("addPrice", addPrice);
				send2.put("merchantsPrice", merchantsPrice);
				send2.put("indentId", indentId);
				send2.put("relievedBao", relievedBao);
				merchantsDao.updateIndentAZ(send2);
				Double wallet = Arith.sub((Double) map2.get("wallet"), Arith.add(merchantsPrice, addPrice));
				Map<String, Object> wat = new HashMap<>();
				wat.put("wallet", wallet);
				wat.put("merchantsId", merchantsId);
				int result = merchantsDao.updateWalletD(wat);
				merchantsDao.updateIndentStatusYes(indentId);
				//记录本次记录
				if(result>0){
					/*merchantsId, indentId, 
					  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
					  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
					merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
							(Integer)map2.get("type"), merchantsPrice, addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
							null, null, TypeOfIndent.INSTALL.getIndex(), 1, "安装订单余额支付",null, 0, PayMethod.BALABCEPAY.getMethod());
				}
				// 根据订单号查询订单信息
				Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
				indentMap.put("number", merchantsDao.selectGoodsNum(indentId));
				Jiguang.JpushIndent(indentMap);// 通过极光推送订单
				// 将本次钱包余额记录插入数据库peopleId,indentId,peopleType,mainMoney,addMoney,subMoney,finalGetMoney,
			} else if (type == 2) {// 维修订单
				logger.error("=====================================余额支付维修订单=========================================");
				// 根据订单号查询一些订单的信息
				Map<String, Object> map = merchantsDao.selectIndent(indentId);
				addPrice = Arith.add(addPrice, (Double) map.get("addPrice"));
				Double merchantsPrice = (Double) map.get("merchantsPrice");
				Double indentPrice = (Double) map.get("indentPrice");
				Double workerRealPrice = (Double) map.get("workerRealPrice");
				Double merchantsRealPrice = (Double) map.get("merchantsRealPrice");
				// 查询电机价钱
				// 获取市
				// String city = (String) map.get("city");
				if (relievedBao == 1) {
					// 查询安心宝价格
					Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");
					merchantsPrice = Arith.add(merchantsPrice, relievedPrice);
				}
				// 根据市获取电机每台单价 根据电机数量计算多少钱
				Double dianjiPrice = (Double) merchantsPriceMap.get("motorPrice");
				Double dianjiPriceGR = (Double) workerPriceMap.get("motorPrice");
				merchantsPrice = Arith.add(merchantsPrice, Arith.mul(motorNum, dianjiPrice));
				indentPrice = Arith.add(indentPrice, Arith.mul(motorNum, dianjiPriceGR));
                workerRealPrice = Arith.add(workerRealPrice, Arith.mul(motorNum, dianjiPriceGR));
				merchantsRealPrice = Arith.add(merchantsRealPrice, Arith.mul(motorNum, dianjiPrice));
				// 根据璧钩数量计算璧钩价格
				Double bigouPrice = (Double) merchantsPriceMap.get("crampetPrice");
				Double bigouPriceGR = (Double) workerPriceMap.get("crampetPrice");
				merchantsPrice = Arith.add(merchantsPrice, Arith.mul(bigouNum, bigouPrice));
				indentPrice = Arith.add(indentPrice, Arith.mul(bigouNum, bigouPriceGR));
                workerRealPrice = Arith.add(workerRealPrice,Arith.mul(bigouNum, bigouPriceGR));
				merchantsRealPrice = Arith.add(merchantsRealPrice,Arith.mul(bigouNum, bigouPrice));
				// 根据四爪钩数量计算四爪钩价格
				Double sizhuagouPrice = (Double) merchantsPriceMap.get("fourClawPrice");
				Double sizhuagouPriceGR = (Double) workerPriceMap.get("fourClawPrice");
				merchantsPrice = Arith.add(merchantsPrice, Arith.mul(sizhuagouNum, sizhuagouPrice));
				indentPrice = Arith.add(indentPrice, Arith.mul(sizhuagouNum, sizhuagouPriceGR));
                workerRealPrice = Arith.add(workerRealPrice,Arith.mul(sizhuagouNum, sizhuagouPriceGR));
				merchantsRealPrice = Arith.add(merchantsRealPrice,Arith.mul(sizhuagouNum, sizhuagouPrice));
				// 修改订单价格
				Map<String, Object> send2 = new HashMap<>();
				send2.put("bigouNum", bigouNum);
				send2.put("sizhuagouNum", sizhuagouNum);
				send2.put("indentPrice", indentPrice);
				send2.put("motorNum", motorNum);
				send2.put("addPrice", addPrice);
				send2.put("merchantsPrice", merchantsPrice);
				send2.put("indentId", indentId);
				send2.put("workerRealPrice", workerRealPrice);
				send2.put("merchantsRealPrice", merchantsRealPrice);
				send2.put("relievedBao", relievedBao);
				merchantsDao.updateIndent(send2);
				Double wallet = Arith.sub((Double) map2.get("wallet"), Arith.add(merchantsPrice, addPrice));
				Map<String, Object> wat = new HashMap<>();
				wat.put("wallet", wallet);
				wat.put("merchantsId", merchantsId);
				int result = merchantsDao.updateWalletD(wat);
				merchantsDao.updateIndentStatusYes(indentId);
				//记录本次记录
				if(result>0){
					/*merchantsId, indentId, 
					  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
					  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
					merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
							(Integer)map2.get("type"), merchantsPrice, addPrice, null, null, Arith.add(merchantsPrice, addPrice), 
							null, null, TypeOfIndent.REPAIR.getIndex(), 1, "维修订单余额支付",null, 0, PayMethod.BALABCEPAY.getMethod());
				}
				// 根据订单号查询订单信息
				Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
				Jiguang.JpushIndent(indentMap);// 通过极光推送订单
			} else if (type == 3) {// 加价悬赏 3加价悬赏没有安心宝(或者之前有) 5有安心宝需付安心宝的钱
				logger.error("=======================================余额加价悬赏=========================================");
				// 根据订单号查询一些订单的信息
				Map<String, Object> map = merchantsDao.selectIndent(indentId);
				Integer relievedBaoY = (Integer) map.get("relievedBao");
				Double moneyAddPrice = addPrice;
				// 查询安心宝价格
				Double relievedPrice = (Double) merchantsPriceMap.get("relievedPrice");
				if (relievedBaoY == 0) {// 之前没选
					if (relievedBao == 0) {// 还是没选
						Double wallet = Arith.sub((Double) map2.get("wallet"), moneyAddPrice);
						Map<String, Object> wat = new HashMap<>();
						wat.put("wallet", wallet);
						wat.put("merchantsId", merchantsId);
						int result = merchantsDao.updateWalletD(wat);
						Double addPrice2 = (Double) map.get("addPrice");
						moneyAddPrice = Arith.add(addPrice2, moneyAddPrice);
						// 修改订单加价钱数
						Map<String, Object> send2 = new HashMap<>();
						send2.put("indentId", indentId);
						send2.put("addPrice", moneyAddPrice);
						merchantsDao.updateAddPrice(send2);
						// 根据订单号查询订单信息
						Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
						if ((int) map.get("type") == 1) {// 订单类型0测量 1安装 2维修
															// 3经销商自主测量的'
							indentMap.put("number", merchantsDao.selectGoodsNum(indentId));
						}
						Jiguang.JpushIndent(indentMap);// 通过极光推送订单
						//记录本次记录
						if(result>0){
							/*merchantsId, indentId, 
							  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
							  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
							merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
									(Integer)map2.get("type"), null, addPrice, null, null,  addPrice, 
									null, null, TypeOfIndent.ADD_PRICE.getIndex(), 1, "订单加价悬赏",null, 0, PayMethod.BALABCEPAY.getMethod());
						}
						
					} else {// 这次选了
						Double wallet = Arith.sub((Double) map2.get("wallet"), Arith.add(moneyAddPrice, relievedPrice));
						Map<String, Object> wat = new HashMap<>();
						wat.put("wallet", wallet);
						wat.put("merchantsId", merchantsId);
						int result=merchantsDao.updateWalletD(wat);
						Double merchantsPrice = Arith.add((Double) map.get("merchantsPrice"), relievedPrice);
						Double addPrice2 = (Double) map.get("addPrice");
						moneyAddPrice = Arith.add(addPrice2, moneyAddPrice);
						// 修改订单加价钱数
						Map<String, Object> send2 = new HashMap<>();
						send2.put("indentId", indentId);
						send2.put("addPrice", moneyAddPrice);
						send2.put("relievedBao", 1);
						send2.put("merchantsPrice", merchantsPrice);
						merchantsDao.updateAddPrice2(send2);
						// 根据订单号查询订单信息
						Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
						if ((int) map.get("type") == 1) {// 订单类型0测量 1安装 2维修
															// 3经销商自主测量的'
							indentMap.put("number", merchantsDao.selectGoodsNum(indentId));
						}
						Jiguang.JpushIndent(indentMap);// 通过极光推送订单
						//记录本次记录
						if(result>0){
							/*merchantsId, indentId, 
							  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
							  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
							merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
									(Integer)map2.get("type"), relievedPrice, addPrice, null, null, Arith.add(relievedPrice, addPrice), 
									null, null, TypeOfIndent.ADD_PRICE.getIndex(), 1, "维修订单余额支付",null, 0, PayMethod.BALABCEPAY.getMethod());
						}
						
					}
				} else {// 选了
					// moneyAddPrice = Arith.add(moneyAddPrice, relievedPrice);
					// 算错了 不应该加安心宝
					Double wallet = Arith.sub((Double) map2.get("wallet"), moneyAddPrice);
					Map<String, Object> wat = new HashMap<>();
					wat.put("wallet", wallet);
					wat.put("merchantsId", merchantsId);
					int result = merchantsDao.updateWalletD(wat);
					
					Double addPrice2 = (Double) map.get("addPrice");
					// Double merchantsPrice =
					// Arith.add((Double)map.get("merchantsPrice"),relievedPrice);
					moneyAddPrice = Arith.add(addPrice2, moneyAddPrice);
					// 修改订单加价钱数
					Map<String, Object> send2 = new HashMap<>();
					send2.put("indentId", indentId);
					send2.put("addPrice", moneyAddPrice);
					send2.put("relievedBao", 1);
					send2.put("merchantsPrice", map.get("merchantsPrice"));
					merchantsDao.updateAddPrice2(send2);
					// 根据订单号查询订单信息
					Map<String, Object> indentMap = merchantsDao.selectIndent(indentId);
					if ((int) map.get("type") == 1) {// 订单类型0测量 1安装 2维修
														// 3经销商自主测量的'
						indentMap.put("number", merchantsDao.selectGoodsNum(indentId));
					}
					Jiguang.JpushIndent(indentMap);// 通过极光推送订单
					//记录本次记录
					if(result>0){
						/*merchantsId, indentId, 
						  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
						  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
						merchantswalletRecordService.insertMerchantsWalletRecord(merchantsId, indentId, 
								(Integer)map2.get("type"), null, addPrice, null, null, addPrice, 
								null, null, TypeOfIndent.ADD_PRICE.getIndex(), 1, "订单加价悬赏",null, 0, PayMethod.BALABCEPAY.getMethod());
					}
				}
			} else {// type=4 为补差价
				logger.error("=======================================余额补差价=========================================");
				JSONArray idArray= JSONObject.parseArray(differenceIds);
				//找出本次需要进行补差价的记录differenceId indentId differencePrice cause ispay
				List<Map<String,Object>> differenceList = merchantsDao.selectDifferences(merchantsId,idArray);
				//判断总价是否和传来的总金额是否一样
				boolean flag = getToatalMoneyIsFlag(differenceList,totalMoney);
				if(!flag){
					buluResult.setStatus(1);
					buluResult.setMessage("差价总金额有误,请核对差价总金额");
					return buluResult;
				}
				//余额支付差价
				for(int a = 0;a<differenceList.size();a++){
					Double toWorker = (Double)differenceList.get(a).get("differencePrice");
					Integer workerId = (Integer)differenceList.get(a).get("workerId");
					Integer differenceIndentId = (Integer)differenceList.get(a).get("indentId");
					int update = updateDifferenceToWorker(differenceIndentId,toWorker,workerId);
					// 把状态改为已支付
					if(update>0){
						// 把状态改为已支付
						merchantsDao.updateDifferenceIspay((Integer) differenceList.get(a).get("differenceId"));
					}
				}
				Double wallet = Arith.sub((Double) map2.get("wallet"), totalMoney);
				Map<String, Object> wat = new HashMap<>();
				wat.put("wallet", wallet);
				wat.put("merchantsId", merchantsId);
				merchantsDao.updateWalletD(wat);
			}
			buluResult.setStatus(0);
		} else {// 密码错误
			buluResult.setStatus(1);
			buluResult.setMessage("密码不正确!");
		}
		return buluResult;
	}
	/**
	 * 计算补差价是否和数据库一样多的总价
	 * @param differenceList
	 * @param totalMoney
	 * @return
	 */
	private boolean getToatalMoneyIsFlag(List<Map<String, Object>> differenceList, Double totalMoney) {
		Double differenceTotalMoney = 0.00;
		for(int a = 0;a<differenceList.size();a++){
			Double differencePrice = (Double)differenceList.get(a).get("differencePrice");
			differenceTotalMoney = Arith.add(differenceTotalMoney, differencePrice);
		}
		return differenceTotalMoney.compareTo(totalMoney)==0;
	}

	/**
	 * 在补差价的时候补给订单对应的工人的差价钱
	 * @param indentId
	 * @param toWorker
	 * @param workerId
	 * @return
	 */
	private int updateDifferenceToWorker(Integer indentId, Double toWorker,Integer workerId) {
		Double workerWallet = workerDao.selectWallet(workerId);
		workerWallet = Arith.add(workerWallet, toWorker);
		//给工人钱包加上商家取消扣除的钱
		Map<String, Object> send = new HashMap<>();
		send.put("workerId", workerId);
		send.put("wallet", workerWallet);
		//更新工人钱包
		workerDao.updateWalletComple(send);
		int update = workerWalletRecordService.insertWorkerWalletRecord(workerId, indentId, 2,
				toWorker, null, null, toWorker, null, null,null, TypeOfIndent.PRICE_DIFFERENCE.getIndex(), 1, "商家支付补差价", 0, "余额获取补差价");
		return update>0?update:0;
	}

	// 查询银行卡微信支付宝
	public BuluResult selectBangding(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 查询有没有银行卡
		Integer yinhangkaNum = merchantsDao.selectYinhangka(merchantsId);
		// 查询有没有微信
		Integer weixinNum = merchantsDao.selectWeixin(merchantsId);
		// 查询有没有支付宝
		Integer zhifubaoNum = merchantsDao.selectZhifubao(merchantsId);
		Map<String, Object> send = new HashMap<>();
		if (yinhangkaNum != 0) {
			send.put("yinhangka", 1);
		} else {
			send.put("yinhangka", 0);
		}
		if (weixinNum == 1) {
			send.put("weixin", 1);
		} else {
			send.put("weixin", 0);
		}
		if (zhifubaoNum == 1) {
			send.put("zhifubao", 1);
		} else {
			send.put("zhifubao", 0);
		}
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setData(send);
		return buluResult;
	}

	// 确定是商家申请提现
	public BuluResult submitWithdrawal(HttpServletRequest request, Double money, Integer status, Integer bankCardId,
			String weixin, String zhifubao, String account, String name) {
		//logger.error("=======================================开始提现=========================================");
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// wallet,password,weiYi
		Map<String, Object> map2 = merchantsDao.selectMerchantsWallet(merchantsId);
		BuluResult buluResult = new BuluResult();

		if (money.compareTo(0.00) <= 0) {
			buluResult.setStatus(1);
			logger.error("提现金额输入有误");
			buluResult.setMessage("提现金额格式不正确或者输入为0无效请求");
			return buluResult;
		}

		// 判断商家提现的金钱是否小于等于商家钱包中的钱 //XGH
		if (money.compareTo((Double) map2.get("wallet")) > 0) {
			buluResult.setStatus(1);
			buluResult.setMessage("钱包余额不足，请重新输入提现金额");
			return buluResult;
		} // XGH

		// 判断输入的密码是否正确//XGH
		JSONObject object =getAccountMap(account);
		String password = object.getString("password");
		password = MD5Utils.MD5(password + map2.get("weiyi"));
		if (!password.equals(map2.get("password"))) {
			buluResult.setStatus(1);
			buluResult.setMessage("密码不正确,请重新输入");
			return buluResult;
		}

		// 提现记录参数
		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
		merchantsWalletRecord.setMerchantsId(merchantsId);
		merchantsWalletRecord.setMerchantsType((Integer)map2.get("type"));
		merchantsWalletRecord.setType(TypeOfIndent.WITHDRAWALS.getIndex());
		merchantsWalletRecord.setWalletWithdrawals(money);
		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDateTime());
		merchantsWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(merchantsId,PayMethod.BALABCEPAY.getIndex(),TypeOfIndent.WITHDRAWALS.getIndex()));
		/*MoneyRecord moneyRecord = new MoneyRecord();
		moneyRecord.setPeopleId(merchantsId);
		moneyRecord.setType(3);
		moneyRecord.setMoney(money);
		Date date = new Date();
		moneyRecord.setRecordTime(date);
		moneyRecord.setStatus(status);
		// 商户转账唯一订单号
		String outBizNo = merchantsId + "_" + String.valueOf(new Date().getTime());
		moneyRecord.setOutBizNo(outBizNo);*/
		// 申请提现根据status判断是什么类型的提现
		if (status == 0) {// 0是银行卡
			if (password.equals(map2.get("password"))) {// 密码正确
				// 根据银行卡id查询银行卡名和银行卡号
				Map<String, Object> map = merchantsDao.selectBankCardOne(bankCardId);
				/*moneyRecord.setBoundBank((String) map.get("boundBank"));
				moneyRecord.setBankNumber((String) map.get("bankNumber"));
				// 插入到数据库中
				merchantsDao.insertMoneyRecord(moneyRecord);*/
				buluResult.setStatus(0);
				// 根据id查询钱包余额
				Map<String, Object> map5 = merchantsDao.selectWallet(merchantsId);
				Double wallet = (Double) map5.get("wallet");
				wallet = Arith.sub(wallet, money);
				Map<String, Object> map3 = new HashMap<>();
				map3.put("merchantsId", merchantsId);
				map3.put("wallet", wallet);
				merchantsDao.updateWalletD(map3);
			} else {
				buluResult.setStatus(1);
				buluResult.setMessage("密码错误!");
			}
		} else if (status == 1) {// 1是支付宝
			merchantsWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
			merchantsWalletRecord.setRemark("提现到支付宝");
			merchantsWalletRecord.setAlipayNum(zhifubao);
			Map<String, Object> alipayMap = merchantsDao.selectDefultBank(merchantsId);
			if (alipayMap == null || (String) alipayMap.get("alipayNum") == null
					|| "".equals((String) alipayMap.get("alipayNum"))) {
				alipayMap = new HashMap<>();
				alipayMap.put("peopleId", merchantsId);
				alipayMap.put("type", 1);
				alipayMap.put("status", 1);
				alipayMap.put("alipayNum", zhifubao);
				alipayMap.put("boundBank", "支付宝");
				merchantsDao.insertBankCard(alipayMap);
			}
			// merchantsDao.insertMoneyRecord(moneyRecord);

			// XGH 支付宝提现的申请
			// 执行支付宝转账
			buluResult = alipyFundTransToaccountTransfer(merchantsWalletRecord, zhifubao, money, name, merchantsId);
			// XGH

		} else {// 2是微信
			/*moneyRecord.setWeixin(weixin);
			moneyRecord.setName(name);
			merchantsDao.insertMoneyRecord(moneyRecord);*/
			buluResult.setStatus(0);
			// 根据id查询钱包余额
			Map<String, Object> map = merchantsDao.selectWallet(merchantsId);
			Double wallet = (Double) map.get("wallet");
			wallet = Arith.sub(wallet, money);
			Map<String, Object> map3 = new HashMap<>();
			map3.put("merchantsId", merchantsId);
			map3.put("wallet", wallet);
			merchantsDao.updateWalletD(map3);
		}
		return buluResult;
	}

	/**
	 * 提现业务实现
	 * 
	 * @param zhifubao
	 * @param money
	 * @param name
	 * @param merchantsId
	 */
	private BuluResult alipyFundTransToaccountTransfer(MerchantsWalletRecord merchantsWalletRecord, String zhifubao, Double money,
			String name, Integer merchantsId) {
		//logger.error("=======================================开始请求支付宝=========================================");
		BuluResult buluResult = new BuluResult();
		// 实例化客户端
		AlipayClient alipayClient0 = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8", AlipayConfig.alipay_public_key,
				"RSA2");
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
		// 我们商家的唯一提现流水号
		model.setOutBizNo(merchantsWalletRecord.getOrderNo());
		// 收款方账户类型。
		model.setPayeeType("ALIPAY_LOGONID");
		// 收款方账户。
		model.setPayeeAccount(zhifubao);
		// 转账金额
		DecimalFormat formater = new DecimalFormat("#0.#");
		formater.setRoundingMode(RoundingMode.FLOOR);
		//logger.error(formater.format(Arith.mul(money, Arith.sub(1, 0.006))));
		model.setAmount(formater.format(Arith.mul(money, Arith.sub(1, 0.006))));
		// 付款方真实姓名
		model.setPayerShowName("郑州鹿客互联网科技有限公司");
		// 收款方真实姓名（最长支持100个英文/50个汉字）。
		model.setPayeeRealName(name);
		// 转账备注
		model.setRemark("商家个人提现");
		// 加入请求头
		request.setBizModel(model);
		AlipayFundTransToaccountTransferResponse response = null;
		try {
			Thread.sleep(3000);
			response = alipayClient0.execute(request);
			//logger.error(response.getBody());
			if (response.isSuccess()) {
				//logger.error("=======================================提现成功开始业务=========================================");
				logger.error(JSONObject.parseObject(response.getBody()).get("alipay_fund_trans_toaccount_transfer_response"));
				// 请求成功，把该次请求插入数据库
				insertMoneyRecord(merchantsWalletRecord, money, merchantsId, 1);
				// 返回已经处理成功信息
				buluResult.setStatus(0);
				buluResult.setMessage("提现成功");
			} else {
				// 付款余额不足
				if (response.getCode().equals("40004") && response.getSubCode().equals("PAYER_BALANCE_NOT_ENOUGH")) {
					insertMoneyRecord(merchantsWalletRecord, money, merchantsId, 2);
					buluResult.setStatus(2);
					buluResult.setMessage("提现申请中,请耐心等待...");
					return buluResult;
				}
				BuluResult buluResult2 = alipayFundTransOrderQuery(merchantsWalletRecord);
				if (buluResult2.getStatus() == 0) {
					buluResult.setStatus(0);
					buluResult.setMessage("提现成功");
				} else {
					// 返回转账失败信息
					JSONObject jsonObject = JSONObject.parseObject(response.getBody());
					logger.error(jsonObject.get("alipay_fund_trans_toaccount_transfer_response"));
					buluResult.setStatus(1);
					buluResult.setMessage(response.getSubMsg());
				}

			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			//logger.error("支付宝请求暂停3秒==========================");
			e.printStackTrace();
		}
		return buluResult;
	}

	/**
	 * 提现业务的防止幂等现象
	 * 
	 */
	private BuluResult alipayFundTransOrderQuery(MerchantsWalletRecord merchantsWalletRecord) {
		//logger.error("=======================================提现是否出现幂等现象=========================================");
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8", AlipayConfig.alipay_public_key,
				"RSA2");
		BuluResult buluResult = new BuluResult();
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		AlipayFundTransOrderQueryModel model = new AlipayFundTransOrderQueryModel();
		model.setOutBizNo(merchantsWalletRecord.getOrderNo());
		request.setBizModel(model);
		AlipayFundTransOrderQueryResponse response = null;
		try {
			response = alipayClient.execute(request);
			if (response.isSuccess()) {
				//logger.error("在支付宝找到了本次订单，说明已经转过了但是出现了幂等现象，更新数据库数据返回转账成功结束标志");
				//logger.error(JSONObject.parseObject(response.getBody()).get("alipay_fund_trans_order_query_response"));
				// 请求成功，把该次请求插入数据库
				insertMoneyRecord(merchantsWalletRecord, merchantsWalletRecord.getWalletWithdrawals(), 
						merchantsWalletRecord.getMerchantsId(), 1);
				// 返回信息设置
				buluResult.setStatus(0);
			} else {
				// 数据库中插入一条没有处理的提现记录
				//logger.error("在支付宝没有查到本次转账订单，本次转账在支付宝方没有处理");
				insertMoneyRecord(merchantsWalletRecord,merchantsWalletRecord.getWalletWithdrawals(), 
						merchantsWalletRecord.getMerchantsId(), 0);
				//logger.error(JSONObject.parseObject(response.getBody()).get("alipay_fund_trans_order_query_response"));
				buluResult.setStatus(1);
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return buluResult;
	}
	/**
	 * 提现后来放在一个表格中
	 * @param money
	 * @param merchantsId
	 * @param withdrawalStatus
	 */
	private void insertMoneyRecord(MerchantsWalletRecord merchantsWalletRecord, Double money, Integer merchantsId,
			Integer withdrawalStatus) {
		//logger.error("=======================================提现记录保存到数据库=========================================");
		if (withdrawalStatus == 0) {// 申请提现失败
			merchantsWalletRecord.setStatus(withdrawalStatus);
			merchantsWalletRecord.setFinalLostMoney(money);
			merchantsWalletRecord.setRecordEndTime(DateUtils.getDateTime());
			merchantsWalletRecord.setIsDelete(0);
			merchantswalletRecordService.insertMerchantsWalletRecord(merchantsWalletRecord);
		} else if (withdrawalStatus == 1) {// 提现完成
			merchantsWalletRecord.setStatus(withdrawalStatus);
			merchantsWalletRecord.setFinalLostMoney(money);
			merchantsWalletRecord.setRecordEndTime(DateUtils.getDateTime());
			merchantsWalletRecord.setIsDelete(0);
			merchantswalletRecordService.insertMerchantsWalletRecord(merchantsWalletRecord);
			Map<String, Object> map3 = new HashMap<>();
			map3.put("merchantsId", merchantsId);
			map3.put("wallet", money);
			merchantsDao.updateWalletSub(map3);
		} else if (withdrawalStatus == 2) {// 付款方余额不足
			merchantsWalletRecord.setStatus(withdrawalStatus);
			merchantsWalletRecord.setFinalLostMoney(money);
			merchantsWalletRecord.setIsDelete(0);
			merchantswalletRecordService.insertMerchantsWalletRecord(merchantsWalletRecord);
			Map<String, Object> map3 = new HashMap<>();
			map3.put("merchantsId", merchantsId);
			map3.put("wallet", money);
			merchantsDao.updateWalletSub(map3);
		}
	}
	
/*	// 保存提现记录
	private void insertMoneyRecord(MoneyRecord moneyRecord, Double money, Integer merchantsId,
			Integer withdrawalStatus) {
		//logger.error("=======================================提现记录保存到数据库=========================================");
		if (withdrawalStatus == 0) {// 申请提现
			moneyRecord.setWithdrawalStatus(withdrawalStatus);// 0代表提现没有被处理
			merchantsDao.insertMoneyRecord(moneyRecord);
		} else if (withdrawalStatus == 1) {// 提现完成
			moneyRecord.setWithdrawalStatus(withdrawalStatus);// 1代表提现已经处理
			merchantsDao.insertMoneyRecord(moneyRecord);
			// 提现人钱包减去一定的金额
			// Map<String, Object> map = merchantsDao.selectWallet(merchantsId);
			// Double wallet = Arith.sub((Double) map.get("wallet"), money);
			Map<String, Object> map3 = new HashMap<>();
			map3.put("merchantsId", merchantsId);
			map3.put("wallet", money);
			merchantsDao.updateWalletSub(map3);
		} else if (withdrawalStatus == 2) {// 付款方余额不足
			Map<String, Object> map3 = new HashMap<>();
			map3.put("merchantsId", merchantsId);
			map3.put("wallet", money);
			merchantsDao.updateWalletSub(map3);
			moneyRecord.setWithdrawalStatus(withdrawalStatus);// 2代表付款方余额不足，需要人工转账
			merchantsDao.insertMoneyRecord(moneyRecord);
		}
	}*/

	// 查询补差价
	public BuluResult selectDifference(HttpServletRequest request) {
		String sign = request.getParameter("sign");
		Integer merchantsId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		List<Map<String, Object>> list = merchantsDao.selectDifference(merchantsId);
		BuluResult buluResult = new BuluResult();
		if (list != null && list.size() > 0) {
			buluResult.setStatus(0);
			buluResult.setData(list);
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("暂无数据!");
		}
		return buluResult;
	}

	// 修改商品信息specials="[{specialId:'',panzhuangfangshi=''},{}]"
	public BuluResult updateGoodsXinxi(Integer indentId, Integer goodsId, Integer style, String specials) {
		// 根据商品id修改风格
		Map<String, Object> map = new HashMap<>();
		map.put("goodsId", goodsId);
		map.put("style", style);
		// 修改商品风格
		merchantsDao.updateGoodsStyle(map);
		// 根据特殊id修改配件
		if (specials != null) {
			JSONArray jsonArray = JSONObject.parseArray(specials);
			for (int a = 0; a < jsonArray.size(); a++) {
				JSONObject jsonObject = jsonArray.getJSONObject(a);
				Map<String, Object> peijian = new HashMap<>();
				peijian.put("specialId", jsonObject.get("specialId"));
				peijian.put("panzhuangfangshi", jsonObject.get("panzhuangfangshi"));
				merchantsDao.updateSpecial(peijian);
			}
		}
		// 根据订单号查询市
		// String city = merchantsDao.selectAddressCity(indentId);

		// //根据订单号查询所有商品
		// List<Goods> list = merchantsDao.selectAllGoods(indentId);
		// Double merchantsPrice = 0.0;
		// Double indentPrice = 0.0;
		// for(int a=0;a<list.size();a++){
		// Map<String, Object> send = jisuanAnzhuan(list.get(a), city);
		// merchantsPrice = Arith.add(merchantsPrice,
		// (Double)send.get("merchantsPrice"));
		// indentPrice = Arith.add(indentPrice,
		// (Double)send.get("indentPrice"));
		// }
		// Map<String, Object> charu = new HashMap<>();
		// charu.put("indentId", indentId);
		// charu.put("merchantsPrice", merchantsPrice);
		// charu.put("indentPrice", indentPrice);
		// merchantsDao.updateindentPrice(charu);
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		return buluResult;
	}

	// 查询该区域是否开通
	@Override
	public BuluResult theAreaIsDredge(String city, String workerSpaceCode) {
		BuluResult buluResult = new BuluResult();
		if (workerSpaceCode == null) {
			buluResult.setMessage("parameter_error");
			buluResult.setData(null);
			buluResult.setStatus(1);
		} else {
			List<String> areaCode = merchantsDao.theAreaIsDredge(workerSpaceCode);
			//logger.error("areaCode==" + areaCode);
			if (areaCode.size() > 0) {// 查到该区域就认为此区域已开通
				buluResult.setMessage("该区域已开通");
				Map<String, Object> priceMap = merchantsDao.selectCPriceByCity(city, 1);
				double takeGoodsPrice = (double) priceMap.get("takeGoodsPrice");
				Map<String, Object> map = new HashMap<>();
				map.put("theAreaIsDredge", 1);
				map.put("takeGoodsCost", takeGoodsPrice);
				buluResult.setData(map);
			} else {
				buluResult.setMessage("该区域暂未开通");
				Map<String, Object> map = new HashMap<>();
				map.put("theAreaIsDredge", 0);
				buluResult.setData(map);
			}
			buluResult.setStatus(0);
		}
		return buluResult;
	}

	public String getCodeByCityAndArea(String city, String area) {
		// 查询该区对应的code
		Map<String, String> codeMap = new HashMap<>();
		codeMap.put("city", city);
		codeMap.put("area", area);
		String areaCode = merchantsDao.selectAreaCode(codeMap);
		return areaCode;
	}

	/**
	 * 用户实时充值 只用于用户充值
	 */
	/*public BuluResult submitRecarge(HttpServletRequest request, Double money, Integer infer) {
		//logger.error("=======================================开始充值生成支付宝请求参数========================");
		BuluResult buluResult = new BuluResult();
		// 返回确认充值的订单参数
		String orderInfo = "";
		if (money.compareTo(0.00) <= 0) {
			buluResult.setStatus(1);
			buluResult.setMessage("充值金额输入有误，请重新输入!");
			return buluResult;
		}
		// 获取商家在merchants表中的唯一id
		String sign = request.getParameter("sign");
		Integer peopleId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		// 充值参数
		Recharge recharge = new Recharge();
		recharge.setUserId(peopleId);
		Merchants merchants = merchantsDao.selectMerchantsOneById(peopleId);
		int type = merchants.getType() == 0 ? 2 : 0;
		recharge.setPeopleType(type);// 2代表商家0代表用户
		recharge.setMoney(money);
		String CashType = (type == 2 ? "商家充值" : "用户充值");
		recharge.setCashType(CashType);
		recharge.setBeginTime(new Date());
		recharge.setCashInter(infer);
		recharge.setStatus(0);// 插入充值记录，先不激活0代表充值失败
		recharge.setRechargeId(peopleId + "_" + new Date().getTime());
		if (null == infer) {
			buluResult.setStatus(1);
			buluResult.setMessage("请先选择充值方式!");
			return buluResult;
		} else if (infer == 0) {// 0用户支付宝充值
			// 插入数据库并且将充值状态设置为1,1代表失败(在充值成功以后更改状态)
			rechargeDao.insertRecharge(recharge);
			Map<String, Object> send = new HashMap<>();
			send.put("type", 5);
			orderInfo = AlipayParams.getAlipayParams(recharge.getRechargeId(), money, null, CashType, CashType,
					JSONObject.toJSONString(send));
		} else if (infer == 1) {// 1用户微信支付
			rechargeDao.insertRecharge(recharge);
			// 微信回调参数先不写
		}
		buluResult.setStatus(0);
		buluResult.setData(orderInfo);
		return buluResult;
	}*/
	public BuluResult submitRecarge(HttpServletRequest request, Double money, Integer infer) {
		//logger.error("===============================开始充值生成支付宝请求参数========================");
		//参数准备
		BuluResult buluResult = new BuluResult();
		//判断输入金额是否有误
		if (money.compareTo(0.00) <= 0) {
			buluResult.setStatus(1);
			buluResult.setMessage("充值金额输入有误，请重新输入!");
			return buluResult;
		}
		// 获取商家在merchants表中的唯一id
		String sign = request.getParameter("sign");
		Integer peopleId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 7));
		//插入本次充值记录
		Merchants merchants = merchantsDao.selectMerchantsOneById(peopleId);
		String CashType = merchants.getType()==0?"商家充值":"个人充值";
		/*merchantsId, indentId, 
		  merchantsType,mainMoney, addMoney,subMoney, finalGetMoney, finalLostMoney,
		  walletRecharge,walletWithdrawals,type,status,remark, isDelete, method*/
		int walletRecordId = merchantswalletRecordService.insertMerchantsWalletRecord(peopleId, 
				null, merchants.getType(),null, null, null, money, null, money,null, 
				TypeOfIndent.RECHARGE.getIndex(), 0, CashType,null, 0, PayMethod.ALIPAY.getMethod());
		if(walletRecordId>0){
			// 返回确认充值的订单参数
			String orderInfo = "";
			Map<String,Object> param = new HashMap<>();
			param.put("merchantsWalletRecordId", walletRecordId);
			MerchantsWalletRecord merchantsWalletRecord=merchantswalletRecordService.selectMerchantsWalletRecordById(param);
			if (null == infer) {
				buluResult.setStatus(1);
				buluResult.setMessage("请先选择充值方式!");
				return buluResult;
			} else if (infer == 0) {// 0用户支付宝充值
				Map<String, Object> send = new HashMap<>();
				send.put("type", 5);
				send.put("walletRecordId", walletRecordId);
				send.put("recharge", "merchantsRecharge");
				orderInfo = AlipayParams.getAlipayParams(merchantsWalletRecord.getOrderNo(), money, null, CashType, CashType,
						JSONObject.toJSONString(send));
			} else if (infer == 1) {// 1用户微信支付
				//rechargeDao.insertRecharge(recharge);
				// 微信回调参数先不写
			}
			buluResult.setStatus(0);
			buluResult.setData(orderInfo);
		}else{
			buluResult.setStatus(1);
			buluResult.setMessage("充值记录无法保存,暂时无法充值");
		}
		return buluResult;
	}
	
	
	@Override
	public BuluResult getMerchantRules(HttpServletRequest request) {
		BuluResult buluResult = new BuluResult();
		buluResult.setStatus(0);
		buluResult.setMessage(null);
		Integer queryType = Integer.valueOf(request.getParameter("queryType"));
		Map<String, Object> buluRetMap = new HashMap<String, Object>();
		if (queryType == 0) {
			//logger.error("查询类型为" + queryType);
			List<Map<String, String>> retList = new ArrayList<Map<String, String>>();
			Map<String, String> resultMap = merchantsDao.selectMercantsRules(0);
			Map<String, String> map0 = new HashMap<String, String>();
			map0.put("title", "服务费用");
			map0.put("content", "5元/单");
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("title", "保障范围");
			map1.put("content", resultMap.get("serveScope"));
			Map<String, String> map2 = new HashMap<String, String>();
			map2.put("title", "赔偿范围");
			map2.put("content", resultMap.get("indemnifyScope"));
			Map<String, String> map3 = new HashMap<String, String>();
			map3.put("title", "赔偿额度");
			map3.put("content", "以用户实际损失为准，最高不超过人民币" + resultMap.get("indemnifyLimit") + "元");
			Map<String, String> map4 = new HashMap<String, String>();
			map4.put("title", "所需资料");
			map4.put("content", resultMap.get("requiredInfo"));
			Map<String, String> map5 = new HashMap<String, String>();
			map5.put("title", "索赔时效");
			map5.put("content", resultMap.get("claimTime"));
			retList.add(map0);
			retList.add(map1);
			retList.add(map2);
			retList.add(map3);
			retList.add(map4);
			retList.add(map5);
			// 准备数据
			buluRetMap.put("summary", resultMap.get("summary"));
			buluRetMap.put("relievedBaoRules", retList);
			buluRetMap.put("declareContent", resultMap.get("declareContent"));
		} else {
			Map<String, String> selectMercantsRules = merchantsDao.selectMercantsRules(1);
			buluRetMap.put("cautionSummary", "以用户实际损失为准，最高不超过人民币" + selectMercantsRules + "元。");
			logger.error(selectMercantsRules);
		}
		buluResult.setData(buluRetMap);
		return buluResult;
	}

}
